-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker_rpc_linux.go
63 lines (52 loc) · 1.3 KB
/
worker_rpc_linux.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/go-resty/resty/v2"
)
const (
idFormat = "20060102150405-.999"
)
type rpcResponse struct {
Result json.RawMessage `json:"Result"`
}
func generateId() string {
id := time.Now().Format(idFormat)
return strings.ReplaceAll(id, ".", "")
}
func (*Worker) jsonRpcSendRequest(url, method string, params, response interface{}) error {
request := resty.New().NewRequest()
request.SetResult(new(rpcResponse))
request.SetHeaders(map[string]string{
"Accept": "application/json",
"Content-Type": "application/json",
})
request.SetBody(struct {
Id string `json:"id"`
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params interface{} `json:"params"`
}{
Id: generateId(),
JSONRPC: "2.0",
Method: method,
Params: params,
})
resp, err := request.Post(url)
switch {
case err == nil && resp.StatusCode() != http.StatusOK:
err = fmt.Errorf("unexpected response code: %s", resp.Status())
fallthrough
case err != nil:
return fmt.Errorf("send JSON-RPC request: %w", err)
default:
rpcResp := resp.Result().(*rpcResponse)
if err = json.Unmarshal(rpcResp.Result, response); err != nil {
return fmt.Errorf("unmarshal JSON-RPC result: %w", err)
}
return nil
}
}