forked from shenghui0779/sdk-go
/
http.go
285 lines (231 loc) ยท 7.05 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
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
package wx
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"net/url"
"time"
)
// httpSetting http request setting
type httpSetting struct {
headers map[string]string
cookies []*http.Cookie
close bool
}
// HTTPOption configures how we set up the http request.
type HTTPOption func(s *httpSetting)
// WithHTTPHeader specifies the header to http request.
func WithHTTPHeader(key, value string) HTTPOption {
return func(s *httpSetting) {
s.headers[key] = value
}
}
// WithHTTPCookies specifies the cookies to http request.
func WithHTTPCookies(cookies ...*http.Cookie) HTTPOption {
return func(s *httpSetting) {
s.cookies = cookies
}
}
// WithHTTPClose specifies close the connection after
// replying to this request (for servers) or after sending this
// request and reading its response (for clients).
func WithHTTPClose() HTTPOption {
return func(s *httpSetting) {
s.close = true
}
}
// UploadForm is the interface for http upload.
type UploadForm interface {
// Write writes fields to multipart writer
Write(w *multipart.Writer) error
}
// FormFileFunc writes file content to multipart writer.
type FormFileFunc func(w io.Writer) error
type formfile struct {
fieldname string
filename string
filefunc FormFileFunc
}
type uploadform struct {
formfiles []*formfile
formfields map[string]string
}
func (f *uploadform) Write(w *multipart.Writer) error {
if len(f.formfiles) == 0 {
return errors.New("empty file field")
}
for _, v := range f.formfiles {
part, err := w.CreateFormFile(v.fieldname, v.filename)
if err != nil {
return err
}
if err = v.filefunc(part); err != nil {
return err
}
}
for name, value := range f.formfields {
if err := w.WriteField(name, value); err != nil {
return err
}
}
return nil
}
// UploadField configures how we set up the upload from.
type UploadField func(f *uploadform)
// WithFormFile specifies the file field to upload from.
func WithFormFile(fieldname, filename string, fn FormFileFunc) UploadField {
return func(f *uploadform) {
f.formfiles = append(f.formfiles, &formfile{
fieldname: fieldname,
filename: filename,
filefunc: fn,
})
}
}
// WithFormField specifies the form field to upload from.
func WithFormField(fieldname, fieldvalue string) UploadField {
return func(u *uploadform) {
u.formfields[fieldname] = fieldvalue
}
}
// NewUploadForm returns an upload form
func NewUploadForm(fields ...UploadField) UploadForm {
form := &uploadform{
formfiles: make([]*formfile, 0),
formfields: make(map[string]string),
}
for _, f := range fields {
f(form)
}
return form
}
// HTTPClient is the interface for a http client.
type HTTPClient interface {
// Do sends an HTTP request and returns an HTTP response.
// Should use context to specify the timeout for request.
Do(ctx context.Context, method, reqURL string, body []byte, options ...HTTPOption) ([]byte, error)
// Upload issues a UPLOAD to the specified URL.
// Should use context to specify the timeout for request.
Upload(ctx context.Context, reqURL string, form UploadForm, options ...HTTPOption) ([]byte, error)
}
type httpclient struct {
client *http.Client
}
func (c *httpclient) Do(ctx context.Context, method, reqURL string, body []byte, options ...HTTPOption) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, method, reqURL, bytes.NewReader(body))
if err != nil {
return nil, err
}
setting := new(httpSetting)
if len(options) != 0 {
setting.headers = make(map[string]string)
for _, f := range options {
f(setting)
}
}
// headers
if len(setting.headers) != 0 {
for k, v := range setting.headers {
req.Header.Set(k, v)
}
}
// cookies
if len(setting.cookies) != 0 {
for _, v := range setting.cookies {
req.AddCookie(v)
}
}
if setting.close {
req.Close = true
}
resp, err := c.client.Do(req)
if err != nil {
// If the context has been canceled, the context's error is probably more useful.
select {
case <-ctx.Done():
err = ctx.Err()
default:
}
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= http.StatusBadRequest {
io.Copy(ioutil.Discard, resp.Body)
return nil, fmt.Errorf("unexpected status %d", resp.StatusCode)
}
return ioutil.ReadAll(resp.Body)
}
func (c *httpclient) Upload(ctx context.Context, reqURL string, form UploadForm, options ...HTTPOption) ([]byte, error) {
buf := bytes.NewBuffer(make([]byte, 0, 20<<10)) // 20kb
w := multipart.NewWriter(buf)
if err := form.Write(w); err != nil {
return nil, err
}
options = append(options, WithHTTPHeader("Content-Type", w.FormDataContentType()))
// Don't forget to close the multipart writer.
// If you don't close it, your request will be missing the terminating boundary.
if err := w.Close(); err != nil {
return nil, err
}
return c.Do(ctx, http.MethodPost, reqURL, buf.Bytes(), options...)
}
// NewHTTPClient returns a new http client
func NewHTTPClient(client *http.Client) HTTPClient {
return &httpclient{
client: client,
}
}
// NewDefaultClient returns a default http client
func NewDefaultClient(certs ...tls.Certificate) HTTPClient {
return &httpclient{
client: &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 60 * time.Second,
}).DialContext,
TLSClientConfig: &tls.Config{
Certificates: certs,
InsecureSkipVerify: true,
},
MaxIdleConns: 0,
MaxIdleConnsPerHost: 1000,
MaxConnsPerHost: 1000,
IdleConnTimeout: 60 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
},
}
}
// defaultHTTPClient default http client
var defaultHTTPClient = NewDefaultClient()
// HTTPGet issues a GET to the specified URL.
func HTTPGet(ctx context.Context, reqURL string, options ...HTTPOption) ([]byte, error) {
return defaultHTTPClient.Do(ctx, http.MethodGet, reqURL, nil, options...)
}
// HTTPPost issues a POST to the specified URL.
func HTTPPost(ctx context.Context, reqURL string, body []byte, options ...HTTPOption) ([]byte, error) {
return defaultHTTPClient.Do(ctx, http.MethodPost, reqURL, body, options...)
}
// HTTPPostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.
func HTTPPostForm(ctx context.Context, reqURL string, data url.Values, options ...HTTPOption) ([]byte, error) {
options = append(options, WithHTTPHeader("Content-Type", "application/x-www-form-urlencoded"))
return defaultHTTPClient.Do(ctx, http.MethodPost, reqURL, []byte(data.Encode()), options...)
}
// HTTPUpload issues a UPLOAD to the specified URL.
func HTTPUpload(ctx context.Context, reqURL string, form UploadForm, options ...HTTPOption) ([]byte, error) {
return defaultHTTPClient.Upload(ctx, reqURL, form, options...)
}
// HTTPDo sends an HTTP request and returns an HTTP response
func HTTPDo(ctx context.Context, method, reqURL string, body []byte, options ...HTTPOption) ([]byte, error) {
return defaultHTTPClient.Do(ctx, method, reqURL, body, options...)
}