You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.2 KiB

10 years ago
10 years ago
  1. package rpc
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io/ioutil"
  7. "net/http"
  8. "github.com/tendermint/tendermint/binary"
  9. . "github.com/tendermint/tendermint/common"
  10. )
  11. func Call(remote string, method string, params []interface{}, dest interface{}) (interface{}, error) {
  12. // Make request and get responseBytes
  13. request := RPCRequest{
  14. JSONRPC: "2.0",
  15. Method: method,
  16. Params: params,
  17. Id: 0,
  18. }
  19. requestBytes := binary.JSONBytes(request)
  20. requestBuf := bytes.NewBuffer(requestBytes)
  21. httpResponse, err := http.Post(remote, "text/json", requestBuf)
  22. if err != nil {
  23. return dest, err
  24. }
  25. defer httpResponse.Body.Close()
  26. responseBytes, err := ioutil.ReadAll(httpResponse.Body)
  27. if err != nil {
  28. return dest, err
  29. }
  30. log.Debug(Fmt("RPC response: %v", string(responseBytes)))
  31. // Parse response into JSONResponse
  32. response := RPCResponse{}
  33. err = json.Unmarshal(responseBytes, &response)
  34. if err != nil {
  35. return dest, err
  36. }
  37. // Parse response into dest
  38. resultJSONObject := response.Result
  39. errorStr := response.Error
  40. if errorStr != "" {
  41. return dest, errors.New(errorStr)
  42. }
  43. dest = binary.ReadJSONObject(dest, resultJSONObject, &err)
  44. return dest, err
  45. }