-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.go
96 lines (75 loc) · 1.66 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
95
96
package etherscan
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
)
type httpClient interface {
Get(url string) (resp *http.Response, err error)
}
type NetworkID = int
const (
Mainnet = 1
Rinkeby = 3
baseUrlMainnet = "https://api.etherscan.io/api"
baseUrlRinkeby = "https://api-rinkeby.etherscan.io/api"
)
type Client struct {
c httpClient
baseURL string
apiKey string
}
func NewClient(networkID NetworkID, apiKey string) (*Client, error) {
url, err := urlByNetworkID(networkID)
if err != nil {
return nil, err
}
return &Client{
c: http.DefaultClient,
baseURL: url,
apiKey: apiKey,
}, nil
}
func (c *Client) Account(address string) (*AccountResponse, error) {
params := map[string]string{
"module": "account",
"action": "balance",
"address": address,
"tag": "latest",
}
resp, err := c.get(params)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var accountResp AccountResponse
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&accountResp)
return &accountResp, err
}
func (c *Client) get(params map[string]string) (*http.Response, error) {
query := c.buildQuery(params)
url, err := url.Parse(c.baseURL)
if err != nil {
return nil, err
}
url.RawQuery = query
resp, err := c.c.Get(url.String())
if err != nil {
return resp, err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
resp.Body.Close()
return resp, fmt.Errorf("bad status code %d", resp.StatusCode)
}
return resp, nil
}
func (c *Client) buildQuery(params map[string]string) string {
v := url.Values{}
for key, value := range params {
v.Set(key, value)
}
v.Set("apikey", c.apiKey)
return v.Encode()
}