-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
80 lines (68 loc) · 1.45 KB
/
http.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
package steemutil
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
type RequestData struct {
Id uint `json:"id"`
JsonRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params []any `json:"params"`
}
type ResponseData struct {
Id uint `json:"id"`
JsonRPC string `json:"jsonrpc"`
Result any `json:"result"`
}
type IClient interface {
Send(RequestData) (ResponseData, error)
}
type Client struct {
Api string
Timeout uint
Client *http.Client
}
func (c *Client) Send(data RequestData) (res ResponseData, err error) {
// Convert the data to JSON
jsonData, err := json.Marshal(data)
if err != nil {
return
}
// Set up the HTTP request
req, err := http.NewRequest("POST", c.Api, strings.NewReader(string(jsonData)))
if err != nil {
return
}
// Set the request headers
req.Header.Set("Content-Type", "application/json")
// TODO: timeout
// Send the request and get the response
resp, err := c.Client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
// Check http response status
if resp.StatusCode != http.StatusOK {
fmt.Println("Error:", resp.Status)
return
}
// Parse response result
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
err = json.Unmarshal(responseBody, &res)
return
}
func GetClient(api string, timeout uint) (client IClient) {
client = &Client{
Api: api,
Timeout: timeout,
Client: &http.Client{},
}
return client
}