-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
76 lines (63 loc) · 1.27 KB
/
api.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
package bitpay
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type apiClient struct {
client *http.Client
url string
token string
}
type Error struct {
Code string `json:"code"`
Message string `json:"error"`
}
func (e *Error) Error() string {
return fmt.Sprintf("[%s] %s", e.Code, e.Message)
}
func newAPIClient(url string, token string) *apiClient {
return &apiClient{
client: &http.Client{
Timeout: time.Second * 30,
},
url: url,
token: token,
}
}
func (c *apiClient) send(path, method string, params, out any) error {
var reader io.Reader
if params != nil {
b, _ := json.Marshal(params)
m := map[string]any{}
json.Unmarshal(b, &m)
m["token"] = c.token
b, _ = json.Marshal(m)
reader = bytes.NewReader(b)
}
req, err := http.NewRequest(method, c.url+path, reader)
if err != nil {
return err
}
req.Header.Set("User-Agent", "bitpay-go")
req.Header.Set("Content-Type", "application/json")
res, err := c.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
var resErr Error
if err := json.NewDecoder(res.Body).Decode(&resErr); err != nil {
return err
}
return &resErr
}
if err := json.NewDecoder(res.Body).Decode(out); err != nil {
return err
}
return nil
}