-
Notifications
You must be signed in to change notification settings - Fork 233
/
http.go
112 lines (94 loc) · 2.21 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package flypg
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"time"
"github.com/PuerkitoBio/rehttp"
"github.com/superfly/flyctl/agent"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/terminal"
)
type Client struct {
httpClient *http.Client
BaseURL string
}
// NewFromInstance creates a new Client that targets a specific instance(address)
func NewFromInstance(address string, dialer agent.Dialer) *Client {
url := fmt.Sprintf("http://%s:5500", address)
terminal.Debugf("flypg will connect to: %s\n", url)
return &Client{
httpClient: newHttpClient(dialer),
BaseURL: url,
}
}
func newHttpClient(dialer agent.Dialer) *http.Client {
transport := &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, network, addr)
},
}
retry := rehttp.NewTransport(
transport,
rehttp.RetryAll(
rehttp.RetryMaxRetries(3),
rehttp.RetryAny(
rehttp.RetryTemporaryErr(),
rehttp.RetryStatuses(502, 503),
),
),
rehttp.ExpJitterDelay(100*time.Millisecond, 1*time.Second),
)
logging := &api.LoggingTransport{
InnerTransport: retry,
Logger: terminal.DefaultLogger,
}
return &http.Client{Transport: logging}
}
func (c *Client) Do(ctx context.Context, method, path string, in, out interface{}) error {
req, err := c.NewRequest(path, method, in)
if err != nil {
return err
}
req = req.WithContext(ctx)
res, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode > 299 {
return newError(res.StatusCode, res)
}
if out != nil {
if err := json.NewDecoder(res.Body).Decode(out); err != nil {
return err
}
}
return nil
}
func (c *Client) NewRequest(path string, method string, in interface{}) (*http.Request, error) {
var (
body io.Reader
headers = make(map[string][]string)
)
if in != nil {
b, err := json.Marshal(in)
if err != nil {
return nil, err
}
headers = map[string][]string{
"Content-Type": {"application/json"},
}
body = bytes.NewReader(b)
}
req, err := http.NewRequest(method, c.BaseURL+path, body)
if err != nil {
return nil, err
}
req.Header = headers
return req, nil
}