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