-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
100 lines (77 loc) · 1.98 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
100
package etf2l
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"github.com/pkg/errors"
)
var (
ErrNotFound = errors.New("Not found (404)")
ErrEOF = errors.New("End of results")
ErrNoResults = errors.New("no rows in result set")
)
type Recursive interface {
IsRecursive() bool
}
type PagedResult interface {
NextURL(r Recursive) (string, error)
}
type Status struct {
Code int `json:"code"`
Message string `json:"message"`
}
func fullURL(path string) string {
return fmt.Sprintf("https://api-v2.etf2l.org%s", path)
}
type Client struct {
sync.RWMutex
}
func New() *Client {
return &Client{}
}
type HTTPExecutor interface {
Do(req *http.Request) (*http.Response, error)
}
func (client *Client) call(ctx context.Context, httpClient HTTPExecutor, path string, body any, receiver any) error {
client.Lock()
defer client.Unlock()
var reqBody io.Reader
if body != nil {
rb, errMarshal := json.Marshal(body)
if errMarshal != nil {
return errors.Wrap(errMarshal, "Failed to marshal payload")
}
reqBody = bytes.NewReader(rb)
}
req, errReq := http.NewRequestWithContext(ctx, http.MethodGet, fullURL(path), reqBody)
if errReq != nil {
return errors.Wrap(errReq, "Failed to create request")
}
req.Header.Add("Content-Type", `application/json`)
req.Header.Add("Accept", "application/json")
resp, errResp := httpClient.Do(req)
if errResp != nil {
return errors.Wrap(errResp, "Failed to call endpoint")
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode == http.StatusTooManyRequests {
return errors.New("Rate limited")
}
if !(resp.StatusCode >= http.StatusOK && resp.StatusCode <= http.StatusIMUsed) {
if resp.StatusCode == http.StatusNotFound {
return ErrNotFound
}
return errors.Errorf("Invalid status code: %s", resp.Status)
}
decoder := json.NewDecoder(resp.Body)
if errJSON := decoder.Decode(&receiver); errJSON != nil {
return errors.Wrap(errJSON, "Failed to unmarshal json payload")
}
return nil
}