-
Notifications
You must be signed in to change notification settings - Fork 3
/
util.go
60 lines (43 loc) · 953 Bytes
/
util.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
package dbl
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
)
type ratelimitResponse struct {
RetryAfter int `json:"retry-after"`
}
func (c *Client) readBody(res *http.Response) ([]byte, error) {
defer res.Body.Close()
if res.StatusCode == 401 {
return nil, ErrUnauthorizedRequest
}
if res.StatusCode != 200 {
return nil, ErrRequestFailed
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode == 429 {
rr := &ratelimitResponse{}
err = json.Unmarshal(body, rr)
if err != nil {
return nil, err
}
c.Lock()
c.RetryAfter = rr.RetryAfter
c.Unlock()
return nil, ErrRemoteRatelimit
}
return body, nil
}
func (c *Client) createRequest(method, endpoint string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, BaseURL+endpoint, body)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", c.token)
return req, nil
}