-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc.go
88 lines (75 loc) · 1.8 KB
/
rpc.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
type RPCRequestPayload struct {
ID string `json:"id"`
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params interface{} `json:"params"`
}
type RpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type RpcResponse struct {
ID string `json:"id"`
JSONRPC string `json:"jsonrpc"`
Result interface{} `json:"result"`
Error *RpcError `json:"error"`
}
type RPCClient struct {
HTTPClient *http.Client
Host string
BasePath string
}
func (c *RPCClient) BaseURL() string {
return fmt.Sprintf("%s/%s", c.Host, c.BasePath)
}
func (c *RPCClient) MakeRequest(ctx context.Context, rpcReq interface{}, result interface{}) error {
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(rpcReq); err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, "POST", c.BaseURL(), buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
rawResp, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer rawResp.Body.Close()
if rawResp.StatusCode != 200 {
// RPC returns 200 unless something went really wrong
return fmt.Errorf("Unknown Error. Code %d", rawResp.StatusCode)
}
resp := RpcResponse{
Result: result,
}
if err := json.NewDecoder(rawResp.Body).Decode(&resp); err != nil {
return err
}
if resp.Result == nil && resp.Error == nil {
return fmt.Errorf("Unable to parse RPC response: %+v", resp)
}
if resp.Error != nil {
return fmt.Errorf("RPC Error. %+v", resp.Error)
}
return nil
}
func NewRPCClient(host string) *RPCClient {
return &RPCClient{
Host: host,
BasePath: "json_rpc",
HTTPClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}