-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
75 lines (63 loc) · 1.45 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
package gasstation
/*
Wraps API for https://docs.ethgasstation.info/
*/
import (
"encoding/json"
"net/http"
"net/url"
"path"
)
type GasStationClient interface {
GetPredictionTable() ([]Prediction, error)
GetGasPrice() (*GasPrice, error)
}
type gasStationClient struct {
baseURI string
httpClient *http.Client
apiKey string
}
const (
DefaultBaseURI = "https://ethgasstation.info/api/"
)
func NewGasStationClient(apikey string) GasStationClient {
return &gasStationClient{
baseURI: DefaultBaseURI,
httpClient: http.DefaultClient,
apiKey: apikey,
}
}
func (c *gasStationClient) Request(httpMethod string, endpoint string, result interface{}) (resp *http.Response, err error) {
requestURL, err := createRequestURL(c.baseURI, endpoint, c.apiKey)
if err != nil {
return resp, err
}
req, err := http.NewRequest(httpMethod, requestURL, nil)
if err != nil {
return resp, err
}
resp, err = c.httpClient.Do(req)
if err != nil {
return resp, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return resp, err
}
decoder := json.NewDecoder(resp.Body)
if err = decoder.Decode(result); err != nil {
return resp, err
}
return resp, nil
}
func createRequestURL(baseURL, endpoint, apiKey string) (string, error) {
u, err := url.Parse(baseURL)
if err != nil {
return "", err
}
u.Path = path.Join(u.Path, endpoint)
q := u.Query()
q.Set("api-key", apiKey)
u.RawQuery = q.Encode()
return u.String(), nil
}