This repository has been archived by the owner on Aug 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsonrpc.go
81 lines (67 loc) · 1.89 KB
/
jsonrpc.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
package syscoinrpc
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"github.com/twinj/uuid"
)
// jsonRPCrequest represents a generic JSON RPC request.
type jsonRPCrequest struct {
JSONRpcVersion string `json:"jsonrpc,required"`
Method string `json:"method,required"`
Params interface{} `json:"params,required"`
ID string `json:"id,required"`
}
// jsonRPCrequest represents a generic JSON RPC response.
type jsonRPCresponse struct {
Result json.RawMessage `json:"result,required"`
Error *errorMessage `json:"error"`
ID string `json:"id,required"`
}
type errorMessage struct {
Code int `json:"code,required"`
Message string `json:"message,required"`
}
func (err *errorMessage) Error() string {
return err.Message
}
// do performs a JSON RPC Call.
// url : The endpoint url.
// method: The name of the method which is going to be called.
// params: The JSON object representing all the params.
func (c *Client) do(method string, params ...interface{} /*json.Marshaler*/) (json.RawMessage, error) {
jsonReq := jsonRPCrequest{
JSONRpcVersion: "1.0",
Method: method,
Params: params,
ID: uuid.NewV4().String(),
}
reqBody, err := json.Marshal(jsonReq)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.url, bytes.NewBuffer(reqBody))
if err != nil {
return nil, err
}
req.SetBasicAuth(c.user, c.pass)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var jsonResp jsonRPCresponse
err = json.Unmarshal(content, &jsonResp)
if err != nil {
return nil, err
}
if jsonResp.Error != nil {
return nil, jsonResp.Error
}
return jsonResp.Result, nil
}