-
Notifications
You must be signed in to change notification settings - Fork 0
/
exchange.go
73 lines (61 loc) · 1.53 KB
/
exchange.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
package entrust
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"strconv"
"time"
log "github.com/sirupsen/logrus"
)
func (c *Client) exchange(path, method string, payload interface{}) ([]byte, error) {
var err error
var jsonPayload []byte
if payload != nil {
jsonPayload, err = json.Marshal(payload)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, APIServer+path, bytes.NewBuffer(jsonPayload))
if err != nil {
return nil, err
}
req.SetBasicAuth(c.username, c.apiKey)
// Debug log before setting authorization header
log.WithFields(log.Fields{
"url": req.URL.String(),
"method": method,
"request": string(jsonPayload),
}).Debug("Request")
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
// Slow down when we hit the rate-limit
if resp.StatusCode == 429 {
var delay int
delay, err = strconv.Atoi(resp.Header.Get("Retry-After"))
if err != nil {
delay = 5
}
log.WithFields(log.Fields{
"rateLimit": resp.Header.Get("X-Rate-Limit-Limit"),
"retryAfter": resp.Header.Get("Retry-After"),
"delay": delay,
}).Info("Request rate-limited, retrying according to intructions")
time.Sleep(time.Duration(delay) * time.Second)
return c.exchange(path, method, payload)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
log.WithFields(log.Fields{
"url": resp.Request.URL.String(),
"status": resp.StatusCode,
"response": string(body),
}).Debug("Response")
return body, nil
}