-
Notifications
You must be signed in to change notification settings - Fork 673
/
client.go
64 lines (52 loc) · 1.33 KB
/
client.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
package jsonrpc
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
// JSONRPCCall executes a 2.0 JSON RPC HTTP Post Request to the provided URL with
// the provided method and parameters, which is compatible with the Ethereum
// JSON RPC Server.
func JSONRPCCall(url, method string, parameters ...interface{}) (Response, error) {
const jsonRPCVersion = "2.0"
params, err := json.Marshal(parameters)
if err != nil {
return Response{}, err
}
req := Request{
JSONRPC: jsonRPCVersion,
ID: float64(1),
Method: method,
Params: params,
}
reqBody, err := json.Marshal(req)
if err != nil {
return Response{}, err
}
reqBodyReader := bytes.NewReader(reqBody)
httpReq, err := http.NewRequest(http.MethodPost, url, reqBodyReader)
if err != nil {
return Response{}, err
}
httpReq.Header.Add("Content-type", "application/json")
httpRes, err := http.DefaultClient.Do(httpReq)
if err != nil {
return Response{}, err
}
if httpRes.StatusCode != http.StatusOK {
return Response{}, fmt.Errorf("Invalid status code, expected: %v, found: %v", http.StatusOK, httpRes.StatusCode)
}
resBody, err := io.ReadAll(httpRes.Body)
if err != nil {
return Response{}, err
}
defer httpRes.Body.Close()
var res Response
err = json.Unmarshal(resBody, &res)
if err != nil {
return Response{}, err
}
return res, nil
}