-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
64 lines (56 loc) · 1.2 KB
/
request.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 kernel
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
)
type MixinNetwork struct {
httpClient *http.Client
node string
}
func NewMixinNetwork(node string) *MixinNetwork {
return &MixinNetwork{
httpClient: &http.Client{Timeout: 30 * time.Second},
node: node,
}
}
func (m *MixinNetwork) Request(method string, params []any) ([]byte, error) {
return m.callRPC(method, params)
}
func (m *MixinNetwork) callRPC(method string, params []any) ([]byte, error) {
body, err := json.Marshal(map[string]any{
"method": method,
"params": params,
})
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", m.node, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Close = true
req.Header.Set("Content-Type", "application/json")
resp, err := m.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result struct {
Data any `json:"data"`
Error any `json:"error"`
}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return nil, err
}
if result.Error != nil {
return nil, fmt.Errorf("ERROR %s", result.Error)
}
if result.Data == nil {
return nil, nil
}
return json.Marshal(result.Data)
}