-
Notifications
You must be signed in to change notification settings - Fork 16
/
client_http.go
60 lines (48 loc) · 1.37 KB
/
client_http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package jsonrpc
import (
"net/http"
httpclient "github.com/consensys/quorum-key-manager/pkg/http/client"
"github.com/consensys/quorum-key-manager/pkg/http/request"
"github.com/consensys/quorum-key-manager/pkg/http/response"
)
// HTTPClient is a connector to a jsonrpc server
type HTTPClient struct {
client httpclient.Client
}
// NewHTTPClient creates a new jsonrpc HTTPClient from an HTTP HTTPClient
func NewHTTPClient(c httpclient.Client) *HTTPClient {
return &HTTPClient{
client: c,
}
}
// Do sends a jsonrpc request over the underlying HTTP client and returns a jsonrpc response
func (c *HTTPClient) Do(reqMsg *RequestMsg) (*ResponseMsg, error) {
err := reqMsg.Validate()
if err != nil {
return nil, err
}
req, _ := http.NewRequestWithContext(reqMsg.Context(), http.MethodPost, "", nil)
// write request body
err = request.WriteJSON(req, reqMsg)
if err != nil {
return nil, err
}
resp, err := c.client.Do(req)
if err != nil {
return nil, DownstreamError(err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, InvalidDownstreamHTTPStatusError(resp.StatusCode)
}
// Create response and reads body
respMsg := new(ResponseMsg)
err = response.ReadJSON(resp, respMsg)
if err != nil {
return nil, InvalidDownstreamResponse(err)
}
err = respMsg.Validate()
if err != nil {
return nil, InvalidDownstreamResponse(err)
}
return respMsg, nil
}