-
Notifications
You must be signed in to change notification settings - Fork 9
/
client.go
94 lines (81 loc) · 1.69 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package goingecko
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/JulianToledano/goingecko/ping"
)
const apiHeader = "x-cg-demo-api-key"
const proApiHeader = "x-cg-pro-api-key"
type Client struct {
httpClient *http.Client
baseUrl string
apiKey string
apiHeader string
}
func NewClient(httpClient *http.Client, apiKey string, isPro ...bool) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
if isPro != nil {
return &Client{
httpClient: httpClient,
baseUrl: ProBaseURL,
apiKey: apiKey,
apiHeader: proApiHeader,
}
}
return &Client{
httpClient: httpClient,
baseUrl: BaseURL,
apiKey: apiKey,
apiHeader: apiHeader,
}
}
func (c *Client) Close() {
c.httpClient.CloseIdleConnections()
}
func doReq(req *http.Request, client *http.Client) ([]byte, error) {
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if http.StatusOK != resp.StatusCode {
return nil, fmt.Errorf("%s", body)
}
return body, nil
}
// MakeReq HTTP request helper
func (c *Client) MakeReq(url string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if c.apiKey != "" {
req.Header.Add(c.apiHeader, c.apiKey)
}
if err != nil {
return nil, err
}
resp, err := doReq(req, c.httpClient)
if err != nil {
return nil, err
}
return resp, err
}
// Ping /ping endpoint
func (c *Client) Ping() (*ping.Ping, error) {
resp, err := c.MakeReq(fmt.Sprintf("%s/ping", c.baseUrl))
if err != nil {
return nil, err
}
var data *ping.Ping
err = json.Unmarshal(resp, &data)
if err != nil {
return nil, err
}
return data, nil
}