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.

51 lines
1.3 KiB

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