-
Notifications
You must be signed in to change notification settings - Fork 411
/
httputil.go
450 lines (392 loc) · 12.3 KB
/
httputil.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// Copyright (c) 2016-2019 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httputil
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
"github.com/cenkalti/backoff"
"github.com/pressly/chi"
"github.com/uber/kraken/core"
"github.com/uber/kraken/utils/handler"
)
// RoundTripper is an alias of the http.RoundTripper for mocking purposes.
type RoundTripper = http.RoundTripper
// StatusError occurs if an HTTP response has an unexpected status code.
type StatusError struct {
Method string
URL string
Status int
Header http.Header
ResponseDump string
}
// NewStatusError returns a new StatusError.
func NewStatusError(resp *http.Response) StatusError {
defer resp.Body.Close()
respBytes, err := ioutil.ReadAll(resp.Body)
respDump := string(respBytes)
if err != nil {
respDump = fmt.Sprintf("failed to dump response: %s", err)
}
return StatusError{
Method: resp.Request.Method,
URL: resp.Request.URL.String(),
Status: resp.StatusCode,
Header: resp.Header,
ResponseDump: respDump,
}
}
func (e StatusError) Error() string {
if e.ResponseDump == "" {
return fmt.Sprintf("%s %s %d", e.Method, e.URL, e.Status)
}
return fmt.Sprintf("%s %s %d: %s", e.Method, e.URL, e.Status, e.ResponseDump)
}
// IsStatus returns true if err is a StatusError of the given status.
func IsStatus(err error, status int) bool {
statusErr, ok := err.(StatusError)
return ok && statusErr.Status == status
}
// IsCreated returns true if err is a "created", 201
func IsCreated(err error) bool {
return IsStatus(err, http.StatusCreated)
}
// IsNotFound returns true if err is a "not found" StatusError.
func IsNotFound(err error) bool {
return IsStatus(err, http.StatusNotFound)
}
// IsConflict returns true if err is a "status conflict" StatusError.
func IsConflict(err error) bool {
return IsStatus(err, http.StatusConflict)
}
// IsAccepted returns true if err is a "status accepted" StatusError.
func IsAccepted(err error) bool {
return IsStatus(err, http.StatusAccepted)
}
// IsForbidden returns true if statis code is 403 "forbidden"
func IsForbidden(err error) bool {
return IsStatus(err, http.StatusForbidden)
}
// NetworkError occurs on any Send error which occurred while trying to send
// the HTTP request, e.g. the given host is unresponsive.
type NetworkError struct {
err error
}
func (e NetworkError) Error() string {
return fmt.Sprintf("network error: %s", e.err)
}
// IsNetworkError returns true if err is a NetworkError.
func IsNetworkError(err error) bool {
_, ok := err.(NetworkError)
return ok
}
type sendOptions struct {
body io.Reader
timeout time.Duration
acceptedCodes map[int]bool
headers map[string]string
redirect func(req *http.Request, via []*http.Request) error
retry retryOptions
transport http.RoundTripper
ctx context.Context
// This is not a valid http option. It provides a way to override
// parts of the url. For example, url.Scheme can be changed from
// http to https.
url *url.URL
// This is not a valid http option. HTTP fallback is added to allow
// easier migration from http to https.
// In go1.11 and go1.12, the responses returned when http request is
// sent to https server are different in the fallback mode:
// go1.11 returns a network error whereas go1.12 returns BadRequest.
// This causes TestTLSClientBadAuth to fail because the test checks
// retry error.
// This flag is added to allow disabling http fallback in unit tests.
// NOTE: it does not impact how it runs in production.
httpFallbackDisabled bool
}
// SendOption allows overriding defaults for the Send function.
type SendOption func(*sendOptions)
// SendNoop returns a no-op option.
func SendNoop() SendOption {
return func(o *sendOptions) {}
}
// SendBody specifies a body for http request
func SendBody(body io.Reader) SendOption {
return func(o *sendOptions) { o.body = body }
}
// SendTimeout specifies timeout for http request
func SendTimeout(timeout time.Duration) SendOption {
return func(o *sendOptions) { o.timeout = timeout }
}
// SendHeaders specifies headers for http request
func SendHeaders(headers map[string]string) SendOption {
return func(o *sendOptions) { o.headers = headers }
}
// SendAcceptedCodes specifies accepted codes for http request
func SendAcceptedCodes(codes ...int) SendOption {
m := make(map[int]bool)
for _, c := range codes {
m[c] = true
}
return func(o *sendOptions) { o.acceptedCodes = m }
}
// SendRedirect specifies a redirect policy for http request
func SendRedirect(redirect func(req *http.Request, via []*http.Request) error) SendOption {
return func(o *sendOptions) { o.redirect = redirect }
}
type retryOptions struct {
backoff backoff.BackOff
extraCodes map[int]bool
}
// RetryOption allows overriding defaults for the SendRetry option.
type RetryOption func(*retryOptions)
// RetryBackoff adds exponential backoff between retries.
func RetryBackoff(b backoff.BackOff) RetryOption {
return func(o *retryOptions) { o.backoff = b }
}
// RetryCodes adds more status codes to be retried (in addition to the default
// 5XX codes).
//
// WARNING: You better know what you're doing to retry anything non-5XX.
func RetryCodes(codes ...int) RetryOption {
return func(o *retryOptions) {
for _, c := range codes {
o.extraCodes[c] = true
}
}
}
// SendRetry will we retry the request on network / 5XX errors.
func SendRetry(options ...RetryOption) SendOption {
retry := retryOptions{
backoff: backoff.WithMaxRetries(
backoff.NewConstantBackOff(250*time.Millisecond),
2),
extraCodes: make(map[int]bool),
}
for _, o := range options {
o(&retry)
}
return func(o *sendOptions) { o.retry = retry }
}
// DisableHTTPFallback disables http fallback when https request fails.
func DisableHTTPFallback() SendOption {
return func(o *sendOptions) {
o.httpFallbackDisabled = true
}
}
// SendTLS sets the transport with TLS config for the HTTP client.
func SendTLS(config *tls.Config) SendOption {
return func(o *sendOptions) {
if config == nil {
return
}
o.transport = &http.Transport{TLSClientConfig: config}
o.url.Scheme = "https"
}
}
// SendTLSTransport sets the transport with TLS config for the HTTP client.
func SendTLSTransport(transport http.RoundTripper) SendOption {
return func(o *sendOptions) {
o.transport = transport
o.url.Scheme = "https"
}
}
// SendTransport sets the transport for the HTTP client.
func SendTransport(transport http.RoundTripper) SendOption {
return func(o *sendOptions) { o.transport = transport }
}
// SendContext sets the context for the HTTP client.
func SendContext(ctx context.Context) SendOption {
return func(o *sendOptions) { o.ctx = ctx }
}
// Send sends an HTTP request. May return NetworkError or StatusError (see above).
func Send(method, rawurl string, options ...SendOption) (*http.Response, error) {
u, err := url.Parse(rawurl)
if err != nil {
return nil, fmt.Errorf("parse url: %s", err)
}
opts := &sendOptions{
body: nil,
timeout: 60 * time.Second,
acceptedCodes: map[int]bool{http.StatusOK: true},
headers: map[string]string{},
retry: retryOptions{backoff: &backoff.StopBackOff{}},
transport: nil, // Use HTTP default.
ctx: context.Background(),
url: u,
httpFallbackDisabled: false,
}
for _, o := range options {
o(opts)
}
req, err := newRequest(method, opts)
if err != nil {
return nil, err
}
client := &http.Client{
Timeout: opts.timeout,
CheckRedirect: opts.redirect,
Transport: opts.transport,
}
var resp *http.Response
for {
resp, err = client.Do(req)
// Retry without tls. During migration there would be a time when the
// component receiving the tls request does not serve https response.
// TODO (@evelynl): disable retry after tls migration.
if err != nil && req.URL.Scheme == "https" && !opts.httpFallbackDisabled {
originalErr := err
resp, err = fallbackToHTTP(client, method, opts)
if err != nil {
// Sometimes the request fails for a reason unrelated to https.
// To keep this reason visible, we always include the original
// error.
err = fmt.Errorf(
"failed to fallback https to http, original https error: %s,\n"+
"fallback http error: %s", originalErr, err)
}
}
if err != nil ||
(resp.StatusCode >= 500 && !opts.acceptedCodes[resp.StatusCode]) ||
(opts.retry.extraCodes[resp.StatusCode]) {
d := opts.retry.backoff.NextBackOff()
if d == backoff.Stop {
break // Backoff timed out.
}
time.Sleep(d)
continue
}
break
}
if err != nil {
return nil, NetworkError{err}
}
if !opts.acceptedCodes[resp.StatusCode] {
return nil, NewStatusError(resp)
}
return resp, nil
}
// Get sends a GET http request.
func Get(url string, options ...SendOption) (*http.Response, error) {
return Send("GET", url, options...)
}
// Head sends a HEAD http request.
func Head(url string, options ...SendOption) (*http.Response, error) {
return Send("HEAD", url, options...)
}
// Post sends a POST http request.
func Post(url string, options ...SendOption) (*http.Response, error) {
return Send("POST", url, options...)
}
// Put sends a PUT http request.
func Put(url string, options ...SendOption) (*http.Response, error) {
return Send("PUT", url, options...)
}
// Patch sends a PATCH http request.
func Patch(url string, options ...SendOption) (*http.Response, error) {
return Send("PATCH", url, options...)
}
// Delete sends a DELETE http request.
func Delete(url string, options ...SendOption) (*http.Response, error) {
return Send("DELETE", url, options...)
}
// PollAccepted wraps GET requests for endpoints which require 202-polling.
func PollAccepted(
url string, b backoff.BackOff, options ...SendOption) (*http.Response, error) {
b.Reset()
for {
resp, err := Get(url, options...)
if err != nil {
if IsAccepted(err) {
d := b.NextBackOff()
if d == backoff.Stop {
break // Backoff timed out.
}
time.Sleep(d)
continue
}
return nil, err
}
return resp, nil
}
return nil, errors.New("backoff timed out on 202 responses")
}
// GetQueryArg gets an argument from http.Request by name.
// When the argument is not specified, it returns a default value.
func GetQueryArg(r *http.Request, name string, defaultVal string) string {
v := r.URL.Query().Get(name)
if v == "" {
v = defaultVal
}
return v
}
// ParseParam parses a parameter from url.
func ParseParam(r *http.Request, name string) (string, error) {
param := chi.URLParam(r, name)
if param == "" {
return "", handler.Errorf("param %s is required", name).Status(http.StatusBadRequest)
}
val, err := url.PathUnescape(param)
if err != nil {
return "", handler.Errorf("path unescape %s: %s", name, err).Status(http.StatusBadRequest)
}
return val, nil
}
// ParseDigest parses a digest from url.
func ParseDigest(r *http.Request, name string) (core.Digest, error) {
raw, err := ParseParam(r, name)
if err != nil {
return core.Digest{}, err
}
d, err := core.ParseSHA256Digest(raw)
if err != nil {
return core.Digest{}, handler.Errorf("parse digest: %s", err).Status(http.StatusBadRequest)
}
return d, nil
}
func newRequest(method string, opts *sendOptions) (*http.Request, error) {
req, err := http.NewRequest(method, opts.url.String(), opts.body)
if err != nil {
return nil, fmt.Errorf("new request: %s", err)
}
req = req.WithContext(opts.ctx)
if opts.body == nil {
req.ContentLength = 0
}
for key, val := range opts.headers {
req.Header.Set(key, val)
}
return req, nil
}
func fallbackToHTTP(
client *http.Client, method string, opts *sendOptions) (*http.Response, error) {
req, err := newRequest(method, opts)
if err != nil {
return nil, err
}
req.URL.Scheme = "http"
return client.Do(req)
}
func min(a, b time.Duration) time.Duration {
if a < b {
return a
}
return b
}