github.com/okex/exchain@v1.8.0/libs/tendermint/rpc/jsonrpc/client/http_uri_client.go (about) 1 package client 2 3 import ( 4 "io/ioutil" 5 "net/http" 6 7 "github.com/pkg/errors" 8 9 amino "github.com/tendermint/go-amino" 10 11 types "github.com/okex/exchain/libs/tendermint/rpc/jsonrpc/types" 12 ) 13 14 const ( 15 // URIClientRequestID in a request ID used by URIClient 16 URIClientRequestID = types.JSONRPCIntID(-1) 17 ) 18 19 // URIClient is a JSON-RPC client, which sends POST form HTTP requests to the 20 // remote server. 21 // 22 // Request values are amino encoded. Response is expected to be amino encoded. 23 // New amino codec is used if no other codec was set using SetCodec. 24 // 25 // URIClient is safe for concurrent use by multiple goroutines. 26 type URIClient struct { 27 address string 28 client *http.Client 29 cdc *amino.Codec 30 } 31 32 var _ HTTPClient = (*URIClient)(nil) 33 34 // NewURI returns a new client. 35 // An error is returned on invalid remote. 36 // The function panics when remote is nil. 37 func NewURI(remote string) (*URIClient, error) { 38 parsedURL, err := newParsedURL(remote) 39 if err != nil { 40 return nil, err 41 } 42 43 httpClient, err := DefaultHTTPClient(remote) 44 if err != nil { 45 return nil, err 46 } 47 48 parsedURL.SetDefaultSchemeHTTP() 49 50 uriClient := &URIClient{ 51 address: parsedURL.GetTrimmedURL(), 52 client: httpClient, 53 cdc: amino.NewCodec(), 54 } 55 56 return uriClient, nil 57 } 58 59 // Call issues a POST form HTTP request. 60 func (c *URIClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { 61 values, err := argsToURLValues(c.cdc, params) 62 if err != nil { 63 return nil, errors.Wrap(err, "failed to encode params") 64 } 65 66 resp, err := c.client.PostForm(c.address+"/"+method, values) 67 if err != nil { 68 return nil, errors.Wrap(err, "PostForm failed") 69 } 70 defer resp.Body.Close() // nolint: errcheck 71 72 responseBytes, err := ioutil.ReadAll(resp.Body) 73 if err != nil { 74 return nil, errors.Wrap(err, "failed to read response body") 75 } 76 77 return unmarshalResponseBytes(c.cdc, responseBytes, URIClientRequestID, result) 78 } 79 80 func (c *URIClient) Codec() *amino.Codec { return c.cdc } 81 func (c *URIClient) SetCodec(cdc *amino.Codec) { c.cdc = cdc }