-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.go
89 lines (76 loc) · 1.87 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
89
package bitcoinrpc
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type RpcClient struct {
URL string
Username string
Password string
Client *http.Client
}
type RpcRequest struct {
Jsonrpc string `json:"jsonrpc"`
ID int `json:"id"`
Method string `json:"method"`
Params []interface{} `json:"params"`
}
type RpcResponse struct {
Result json.RawMessage `json:"result"`
Error *RpcError `json:"error"`
ID int `json:"id"`
}
// RpcError captures an error returned by the RPC server
type RpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
// NewRpcClient creates a new RpcClient
func NewRpcClient(host string, username string, password string) *RpcClient {
return &RpcClient{
URL: host,
Username: username,
Password: password,
Client: &http.Client{},
}
}
// Do makes an RPC call to the specified method with the provided parameters
func (rpc *RpcClient) Do(method string, params []interface{}) (json.RawMessage, error) {
requestData := RpcRequest{
Jsonrpc: "1.0",
ID: 1,
Method: method,
Params: params,
}
jsonRequest, err := json.Marshal(requestData)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", rpc.URL, bytes.NewBuffer(jsonRequest))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
req.SetBasicAuth(rpc.Username, rpc.Password)
resp, err := rpc.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var rpcResponse RpcResponse
err = json.Unmarshal(body, &rpcResponse)
if err != nil {
return nil, err
}
if rpcResponse.Error != nil {
return nil, fmt.Errorf("RPC error (%d): %s", rpcResponse.Error.Code, rpcResponse.Error.Message)
}
return rpcResponse.Result, nil
}