-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
99 lines (87 loc) · 2.29 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
97
98
99
package xscan
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// predefined endpoints
const (
etherscanUrl = "https://api.etherscan.io/api"
bscscanUrl = "https://api.bscscan.com/api"
polygonscanUrl = "https://api.polygonscan.com/api"
ftmscanUrl = "https://api.ftmscan.com/api"
optimetherscanUrl = "https://api-optimistic.etherscan.io/api"
)
type networkOpts struct {
endpoint string
}
var (
EthOpts = &networkOpts{
endpoint: etherscanUrl,
}
BscOpts = &networkOpts{
endpoint: bscscanUrl,
}
PolygonOpts = &networkOpts{
endpoint: polygonscanUrl,
}
FtmOpts = &networkOpts{
endpoint: ftmscanUrl,
}
OptimEthOpts = &networkOpts{
endpoint: optimetherscanUrl,
}
)
// NewClient is a constructor for the Client struct
func NewClient(netOpts *networkOpts, apiKey string) *Client {
return &Client{
endpoint: netOpts.endpoint,
apiKey: apiKey,
http: new(http.Client),
}
}
// setQueryParam is a helper function to set query parameters to a url including the apikey
func setQueryParam(endpoint *string, module, action, apiKey string, params []map[string]interface{}) {
*endpoint = fmt.Sprintf("%s?module=%s&action=%s", *endpoint, module, action)
for _, param := range params {
for i := range param {
*endpoint = fmt.Sprintf("%s&%s=%v", *endpoint, i, param[i])
}
}
*endpoint = fmt.Sprintf("%s&apikey=%s", *endpoint, apiKey)
}
// doRequest executes the request, the result get returned as a pointer to the caller. It also returns a possible error and the http status code
func (c *Client) doRequest(ctx context.Context, module, action string, expRes interface{}, opts ...map[string]interface{}) (int, error) {
callURL := c.endpoint
if len(opts) > 0 && len(opts[0]) > 0 {
setQueryParam(&callURL, module, action, c.apiKey, opts)
}
fmt.Println(callURL)
req, err := http.NewRequestWithContext(ctx, "GET", callURL, nil)
if err != nil {
return 0, err
}
resp, err := c.http.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
switch resp.StatusCode {
case 200:
if expRes != nil {
err = json.Unmarshal(body, expRes)
if err != nil {
return 0, err
}
}
return resp.StatusCode, nil
default:
return resp.StatusCode, fmt.Errorf("%s", body)
}
}