-
Notifications
You must be signed in to change notification settings - Fork 6
/
http_helpers.go
284 lines (239 loc) · 7.08 KB
/
http_helpers.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package itchio
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
)
func getDebugLevel() int64 {
val, err := strconv.ParseInt(os.Getenv("GO_ITCHIO_DEBUG"), 10, 64)
if err != nil {
return 0
}
return val
}
var (
debugLevel = getDebugLevel()
logRequests = debugLevel >= 1
dumpAPICalls = debugLevel >= 2
)
// Get performs an HTTP GET request to the API
func (c *Client) Get(ctx context.Context, url string) (*http.Response, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
return c.Do(req)
}
// GetResponse performs an HTTP GET request and parses the API response.
func (c *Client) GetResponse(ctx context.Context, url string, dst interface{}) error {
resp, err := c.Get(ctx, url)
if err != nil {
return errors.WithStack(err)
}
err = ParseAPIResponse(dst, resp)
if err != nil {
return errors.WithStack(err)
}
return nil
}
// PostForm performs an HTTP POST request to the API, with url-encoded parameters
func (c *Client) PostForm(ctx context.Context, url string, data url.Values) (*http.Response, error) {
req, err := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return c.Do(req)
}
// PostFormResponse performs an HTTP POST request to the API *and* parses the API response.
func (c *Client) PostFormResponse(ctx context.Context, url string, data url.Values, dst interface{}) error {
resp, err := c.PostForm(ctx, url, data)
if err != nil {
return errors.WithStack(err)
}
err = ParseAPIResponse(dst, resp)
if err != nil {
return errors.WithStack(err)
}
return nil
}
// Do performs a request (any method). It takes care of JWT or API key
// authentication, sets the proper user agent, has built-in retry,
func (c *Client) Do(req *http.Request) (*http.Response, error) {
req.Header.Add("Authorization", c.Key)
req.Header.Set("User-Agent", c.UserAgent)
req.Header.Set("Accept-Language", c.AcceptedLanguage)
req.Header.Set("Accept", "application/vnd.itch.v2")
var res *http.Response
var err error
if logRequests {
fmt.Fprintf(os.Stderr, "%s %s [request]\n", req.Method, req.URL)
}
if dumpAPICalls {
for k, vv := range req.Header {
for _, v := range vv {
fmt.Fprintf(os.Stderr, "[request] %s: %s\n", k, v)
}
}
}
retryPatterns := append(c.RetryPatterns, time.Millisecond)
for _, sleepTime := range retryPatterns {
r := c.Limiter.Reserve()
if !r.OK() {
return nil, errors.Errorf("invalid rate limiter settings")
}
limitDelay := r.Delay()
time.Sleep(limitDelay)
if c.onOutgoingRequest != nil {
c.onOutgoingRequest(req)
}
res, err = c.HTTPClient.Do(req)
if err != nil {
if strings.Contains(err.Error(), "TLS handshake timeout") {
time.Sleep(sleepTime + time.Duration(rand.Int()%1000)*time.Millisecond)
continue
}
return nil, err
}
if res.StatusCode == 503 {
res.Body.Close()
// Rate limited, try again according to patterns.
// following https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#exp-backoff to the letter
actualSleepTime := sleepTime + time.Duration(rand.Int()%1000)*time.Millisecond
if c.onRateLimited != nil {
c.onRateLimited(req, res)
}
if logRequests {
fmt.Fprintf(os.Stderr, "%s %s [rate limited, sleeping %v]\n", req.Method, req.URL, actualSleepTime)
}
time.Sleep(actualSleepTime)
continue
}
break
}
return res, err
}
// MakePath crafts an API url from our configured base URL
func (c *Client) MakePath(format string, a ...interface{}) string {
return c.MakeValuesPath(nil, format, a...)
}
// MakeValuesPath crafts an API url from our configured base URL
func (c *Client) MakeValuesPath(values url.Values, format string, a ...interface{}) string {
base := strings.Trim(c.BaseURL, "/")
subPath := strings.Trim(fmt.Sprintf(format, a...), "/")
path := fmt.Sprintf("%s/%s", base, subPath)
if len(values) == 0 {
return path
}
return fmt.Sprintf("%s?%s", path, values.Encode())
}
func asHTTPCodeError(res *http.Response) error {
if res.StatusCode/100 != 2 {
err := fmt.Errorf("Server error: HTTP %s for %s", res.Status, res.Request.URL.Path)
return err
}
return nil
}
// ParseAPIResponse unmarshals an HTTP response into one of out response
// data structures
func ParseAPIResponse(dst interface{}, res *http.Response) error {
if res == nil || res.Body == nil {
return fmt.Errorf("No response from server")
}
bodyReader := res.Body
defer bodyReader.Close()
body, err := ioutil.ReadAll(bodyReader)
if err != nil {
return errors.WithStack(err)
}
if dumpAPICalls {
fmt.Fprintf(os.Stderr, "[response] %s\n", string(body))
}
intermediate := make(map[string]interface{})
err = json.NewDecoder(bytes.NewReader(body)).Decode(&intermediate)
if err != nil {
if he := asHTTPCodeError(res); he != nil {
return he
}
msg := fmt.Sprintf("JSON decode error: %s\n\nBody: %s\n\n", err.Error(), string(body))
return errors.New(msg)
}
if errorsField, ok := intermediate["errors"]; ok {
if errorsList, ok := errorsField.([]interface{}); ok {
var messages []string
for _, el := range errorsList {
if errorMessage, ok := el.(string); ok {
messages = append(messages, errorMessage)
}
}
if len(messages) > 0 {
return &APIError{Messages: messages, StatusCode: res.StatusCode, Path: res.Request.URL.Path}
}
}
}
if he := asHTTPCodeError(res); he != nil {
return he
}
intermediate = camelifyMap(intermediate)
if dumpAPICalls {
enc := json.NewEncoder(os.Stderr)
enc.SetIndent("[intermediate] ", " ")
_ = enc.Encode(intermediate)
}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
TagName: "json",
Result: dst,
// see https://github.com/itchio/itch/issues/1549
WeaklyTypedInput: true,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeHookFunc(time.RFC3339Nano),
GameHookFunc,
UploadHookFunc,
),
})
if err != nil {
return errors.WithStack(err)
}
err = decoder.Decode(intermediate)
if err != nil {
msg := fmt.Sprintf("mapstructure decode error: %s\n\nBody: %#v\n\n", err.Error(), intermediate)
return errors.New(msg)
}
if res.StatusCode != 200 {
return errors.Errorf("HTTP %v", res.StatusCode)
}
return nil
}
// FindBuildFile looks for an uploaded file of the right type
// in a list of file. Returns nil if it can't find one.
func FindBuildFile(fileType BuildFileType, files []*BuildFile) *BuildFile {
for _, f := range files {
if f.Type == fileType && f.State == BuildFileStateUploaded {
return f
}
}
return nil
}
// FindBuildFileEx looks for an uploaded file of the right type
// and subtype in a list of file. Returns nil if it can't find one.
func FindBuildFileEx(fileType BuildFileType, fileSubType BuildFileSubType, files []*BuildFile) *BuildFile {
for _, f := range files {
if f.Type == fileType && f.SubType == fileSubType && f.State == BuildFileStateUploaded {
return f
}
}
return nil
}