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. log.Debug(Fmt("RPC request to %v: %v", remote, string(requestBytes)))
  22. httpResponse, err := http.Post(remote, "text/json", requestBuf)
  23. if err != nil {
  24. return dest, err
  25. }
  26. defer httpResponse.Body.Close()
  27. responseBytes, err := ioutil.ReadAll(httpResponse.Body)
  28. if err != nil {
  29. return dest, err
  30. }
  31. log.Debug(Fmt("RPC response: %v", string(responseBytes)))
  32. // Parse response into JSONResponse
  33. response := RPCResponse{}
  34. err = json.Unmarshal(responseBytes, &response)
  35. if err != nil {
  36. return dest, err
  37. }
  38. // Parse response into dest
  39. resultJSONObject := response.Result
  40. errorStr := response.Error
  41. if errorStr != "" {
  42. return dest, errors.New(errorStr)
  43. }
  44. dest = binary.ReadJSONObject(dest, resultJSONObject, &err)
  45. return dest, err
  46. }