-
Notifications
You must be signed in to change notification settings - Fork 239
/
http.go
90 lines (73 loc) · 2.06 KB
/
http.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
package api
import (
"context"
"net/http"
"strings"
"time"
"github.com/PuerkitoBio/rehttp"
"github.com/superfly/flyctl/helpers"
"github.com/superfly/flyctl/terminal"
)
var retryErrors = []string{"INTERNAL_ERROR", "read: connection reset by peer"}
func newHTTPClient() (*http.Client, error) {
retryTransport := rehttp.NewTransport(
http.DefaultTransport,
rehttp.RetryAll(
rehttp.RetryMaxRetries(3),
rehttp.RetryAny(
rehttp.RetryTemporaryErr(),
rehttp.RetryIsErr(func(err error) bool {
return err != nil && strings.Contains(err.Error(), "INTERNAL_ERROR")
// Below code was part of retry strategy
// if err == nil {
// return true
// }
// msg := err.Error()
// for _, retryError := range retryErrors {
// if strings.Contains(msg, retryError) {
// return true
// }
// }
// return false
}),
),
),
rehttp.ExpJitterDelay(100*time.Millisecond, 1*time.Second),
)
transport := &LoggingTransport{
innerTransport: retryTransport,
}
httpClient := &http.Client{
Transport: transport,
}
return httpClient, nil
}
type LoggingTransport struct {
innerTransport http.RoundTripper
}
type contextKey struct {
name string
}
var contextKeyRequestStart = &contextKey{"RequestStart"}
func (t *LoggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
ctx := context.WithValue(req.Context(), contextKeyRequestStart, time.Now())
req = req.WithContext(ctx)
t.logRequest(req)
resp, err := t.innerTransport.RoundTrip(req)
if err != nil {
return resp, err
}
t.logResponse(resp)
return resp, err
}
func (t *LoggingTransport) logRequest(req *http.Request) {
terminal.Debugf("--> %s %s %s\n", req.Method, req.URL, req.Body)
}
func (t *LoggingTransport) logResponse(resp *http.Response) {
ctx := resp.Request.Context()
if start, ok := ctx.Value(contextKeyRequestStart).(time.Time); ok {
terminal.Debugf("<-- %d %s (%s)\n", resp.StatusCode, resp.Request.URL, helpers.Duration(time.Now().Sub(start), 2))
} else {
terminal.Debugf("<-- %d %s\n", resp.StatusCode, resp.Request.URL)
}
}