forked from keys-pub/keys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
256 lines (219 loc) · 4.99 KB
/
client.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
// Package http provides an http client for use with checking remote signed
// statements.
package http
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
"unicode/utf8"
)
// ErrTimeout is a timeout error.
type ErrTimeout struct {
error
}
// Err is an HTTP Error.
type Err struct {
Code int
Message string
}
func (e Err) Error() string {
if e.Message != "" {
return e.Message
}
return fmt.Sprintf("http error %d", e.Code)
}
func defaultHTTPClient() *http.Client {
// TODO: Longer timeout?
transport := &http.Transport{
Dial: (&net.Dialer{
Timeout: 10 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
}
client := &http.Client{
Timeout: time.Second * 30,
Transport: transport,
// Important not to follow redirects.
// Twitter may redirect invalid urls with a valid status.
// We do allow a redirect if it's just a case change.
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) == 1 {
if strings.EqualFold(req.URL.String(), via[0].URL.String()) {
return nil
}
}
return http.ErrUseLastResponse
},
}
return client
}
// JSON request.
func JSON(req *Request, v interface{}) error {
hcl := &http.Client{
Timeout: time.Second * 30,
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 10 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
},
}
b, err := doRequest(hcl, req)
if err != nil {
return err
}
return json.Unmarshal(b, v)
}
// Do HTTP request.
func doRequest(client *http.Client, req *Request, options ...func(*http.Request)) ([]byte, error) {
logger.Debugf("Requesting %s %s", req.Method, req.URL)
for _, opt := range options {
opt(req)
}
resp, err := client.Do(req)
switch err := err.(type) {
default:
return nil, err
case nil:
// no error
case *url.Error:
// `http.Client.Do` will return a `url.Error` that wraps a `net.Error`
// when exceeding it's `Transport`'s `ResponseHeadersTimeout`
e1, ok := err.Err.(net.Error)
if ok && e1.Timeout() {
return nil, ErrTimeout{err}
}
return nil, err
case net.Error:
// `http.Client.Do` will return a `net.Error` directly when Dial times
// out, or when the Client's RoundTripper otherwise returns an err
if err.Timeout() {
return nil, ErrTimeout{err}
}
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
logger.Debugf("Response body (len=%d)", len(body))
defer resp.Body.Close()
if resp.StatusCode/200 != 1 {
var errMsg string
if len(body) > 1024 {
body = body[0:1024]
}
if utf8.Valid(body) {
errMsg = string(body)
}
return nil, Err{
Code: resp.StatusCode,
Message: errMsg,
}
}
return body, nil
}
// ErrTemporary means there was a temporary error
type ErrTemporary struct {
msg string
}
// NewErrTemporary creates temporary error.
func NewErrTemporary(msg string) ErrTemporary {
return ErrTemporary{msg: msg}
}
func (e ErrTemporary) Error() string {
return fmt.Sprintf("temporary error: %s", e.msg)
}
// Temporary returns true.
func (e ErrTemporary) Temporary() bool {
return true
}
// Header for request.
type Header struct {
Name string
Value string
}
// Client for HTTP.
type Client interface {
Request(ctx context.Context, req *Request) ([]byte, error)
SetProxy(urs string, fn ProxyFn)
}
type client struct {
httpClient *http.Client
proxies map[string]ProxyFn
}
// NewClient creates a Requestor for HTTP URLs.
func NewClient(opt ...ClientOption) Client {
opts := newClientOptions(opt...)
httpClient := opts.httpClient
if httpClient == nil {
httpClient = defaultHTTPClient()
}
return &client{httpClient: httpClient}
}
// ClientOptions ...
type clientOptions struct {
httpClient *http.Client
}
// ClientOption ...
type ClientOption func(*clientOptions)
// NewClientOptions parses ClientOption.
func newClientOptions(opts ...ClientOption) clientOptions {
var options clientOptions
for _, o := range opts {
o(&options)
}
return options
}
// WithHTTPClient to override http.Client.
func WithHTTPClient(httpClient *http.Client) ClientOption {
return func(o *clientOptions) {
o.httpClient = httpClient
}
}
// ProxyFn for proxy.
type ProxyFn func(ctx context.Context, req *Request) ProxyResponse
// ProxyResponse ...
type ProxyResponse struct {
Skip bool
Body []byte
Err error
}
// ProxyAdd on client.
func (c *client) SetProxy(urs string, fn ProxyFn) {
if c.proxies == nil {
c.proxies = map[string]ProxyFn{}
}
c.proxies[urs] = fn
}
// Request an URL.
func (c *client) Request(ctx context.Context, req *Request) ([]byte, error) {
if c.proxies != nil {
fn := c.proxies[req.URL.String()]
if fn != nil {
pr := fn(ctx, req)
if !pr.Skip {
return pr.Body, pr.Err
}
}
fn = c.proxies[""]
if fn != nil {
pr := fn(ctx, req)
if !pr.Skip {
return pr.Body, pr.Err
}
}
}
req.Header.Set("User-Agent", "keys.pub")
body, err := doRequest(c.httpClient, req)
if err != nil {
logger.Warningf("Failed request: %s", err)
}
return body, err
}