This repository has been archived by the owner on Dec 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
options.go
395 lines (345 loc) · 7.75 KB
/
options.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
package nic
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"path/filepath"
"strings"
"time"
)
type (
// H struct is options for request and http client
H struct {
Params KV
Data KV
Raw string
Headers KV
Cookies KV
Auth KV
Proxy string
JSON KV
Files KV
AllowRedirect bool
Timeout int64
Chunked bool
DisableKeepAlives bool
DisableCompression bool
SkipVerifyTLS bool
}
// KV is used for H struct
KV map[string]interface{}
// when upload a file, we use nic.KV again
// nic.File returns F struct
//
// nic.KV {
// "file1" :"file" : nic.FileFromPath("test.go"),
// "file2" : nic.File("test.go", []byte("package nic")).
// FName("nic.go").
// MIME("text/plain"),
// "token" : "abc",
// }
//
//
// the POST body is:
//
// Content-Type: multipart/form-data; boundary=e7d105eae032bdc774a787f1d874269d04499cb284477d6d77889be73caf
//
// --e7d105eae032bdc774a787f1d874269d04499cb284477d6d77889be73caf
// Content-Disposition: form-data; name="file1"; filename="test.go"
// Content-Type: application/octet-stream
//
// package test
// --e7d105eae032bdc774a787f1d874269d04499cb284477d6d77889be73caf
// Content-Disposition: form-data; name="token"
//
// abc
// --e7d105eae032bdc774a787f1d874269d04499cb284477d6d77889be73caf
// Content-Disposition: form-data; name="file2"; filename="nic.go"
// Content-Type: text/plain
//
// package test
// --e7d105eae032bdc774a787f1d874269d04499cb284477d6d77889be73caf--
//
//
// F struct saves file form information
F struct {
Src []byte
FilePath string
FileName string
MimeType string
}
)
// File returns a new file struct
func File(filename string, src []byte) *F {
return &F{
Src: src,
FileName: filename,
}
}
// FileFromPath returns a file struct from file path
func FileFromPath(path string) *F {
return &F{
FilePath: path,
FileName: filepath.Base(path),
}
}
// FName changes file's filename in multipart form
// invoke it in a chain
func (f *F) FName(filename string) *F {
f.FileName = filename
return f
}
// MIME changes file's mime type in multipart form
// invoke it in a chain
func (f *F) MIME(mimetype string) *F {
f.MimeType = mimetype
return f
}
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}
// Option is the interface implemented by `H` and `*H`
type Option interface {
setRequestOpt(*http.Request) error
setClientOpt(*http.Client) error
}
// could only contains one of Data, Raw, Files, Json
func (h H) isConflict() bool {
count := 0
if h.Data != nil {
count++
}
if h.Raw != "" {
count++
}
if h.Files != nil {
count++
}
if h.JSON != nil {
count++
}
return count > 1
}
func setQuery(req *http.Request, p KV) error {
originURL := req.URL
extendQuery := make([]byte, 0)
for k, v := range p {
kEscaped := url.QueryEscape(k)
vs, ok := v.(string)
if !ok {
return fmt.Errorf("nic: query param %v[%T] must be string type", v, v)
}
vEscaped := url.QueryEscape(vs)
extendQuery = append(extendQuery, '&')
extendQuery = append(extendQuery, []byte(kEscaped)...)
extendQuery = append(extendQuery, '=')
extendQuery = append(extendQuery, []byte(vEscaped)...)
}
// trim the `&`
if originURL.RawQuery == "" {
extendQuery = extendQuery[1:]
}
originURL.RawQuery += string(extendQuery)
return nil
}
func setData(req *http.Request, d KV, chunked bool) error {
data := ""
for k, v := range d {
k = url.QueryEscape(k)
vs, ok := v.(string)
if !ok {
return fmt.Errorf(
"nic: post data %v[%T] must be string type", v, v)
}
vs = url.QueryEscape(vs)
data = fmt.Sprintf("%s&%s=%s", data, k, vs)
}
data = data[1:]
v := strings.NewReader(data)
req.Body = ioutil.NopCloser(v)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if !chunked {
req.ContentLength = int64(v.Len())
}
return nil
}
func setFiles(req *http.Request, files KV, chunked bool) error {
buffer := &bytes.Buffer{}
writer := multipart.NewWriter(buffer)
for name, value := range files {
switch value := value.(type) {
case *F:
mimetype := value.MimeType
if mimetype == "" {
mimetype = "application/octet-stream"
}
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
escapeQuotes(name), escapeQuotes(value.FileName)))
h.Set("Content-Type", mimetype)
part, err := writer.CreatePart(h)
if err != nil {
return err
}
if len(value.Src) != 0 {
_, err = part.Write(value.Src)
if err != nil {
return err
}
} else {
fp, err := os.Open(value.FilePath)
if err != nil {
return err
}
defer fp.Close()
_, err = io.Copy(part, fp)
if err != nil {
return err
}
}
case string:
err := writer.WriteField(name, value)
if err != nil {
return err
}
default:
return ErrFileInfo
}
}
err := writer.Close()
if err != nil {
return err
}
req.Body = ioutil.NopCloser(buffer)
contentType := writer.FormDataContentType()
req.Header.Set("Content-Type", contentType)
if !chunked {
req.ContentLength = int64(buffer.Len())
}
return nil
}
func setJSON(req *http.Request, j KV, chunked bool) error {
jsonV, err := json.Marshal(j)
if err != nil {
return err
}
v := bytes.NewBuffer(jsonV)
req.Body = ioutil.NopCloser(v)
req.Header.Set("Content-Type", "application/json")
if !chunked {
req.ContentLength = int64(v.Len())
}
return nil
}
// set option for http.Request
// data, header, cookie, auth, file, json
func (h H) setRequestOpt(req *http.Request) error {
if h.isConflict() {
return ErrParamConflict
}
if h.Params != nil {
err := setQuery(req, h.Params)
if err != nil {
return err
}
}
if h.Data != nil {
err := setData(req, h.Data, h.Chunked)
if err != nil {
return err
}
}
if h.Raw != "" {
v := strings.NewReader(h.Raw)
req.Body = ioutil.NopCloser(v)
if !h.Chunked {
req.ContentLength = int64(v.Len())
}
}
if h.Headers != nil {
for headerK, headerV := range h.Headers {
headerVS, ok := headerV.(string)
if !ok {
return fmt.Errorf(
"nic: header %v[%T] must be string type",
headerV, headerV)
}
req.Header.Set(headerK, headerVS)
}
}
if h.Cookies != nil {
for cookieK, cookieV := range h.Cookies {
cookieVS, ok := cookieV.(string)
if !ok {
return fmt.Errorf(
"nic: cookie %v[%T] must be string type",
cookieV, cookieV)
}
c := &http.Cookie{
Name: cookieK,
Value: cookieVS,
}
req.AddCookie(c)
}
}
if h.Auth != nil {
for k, v := range h.Auth {
vs, ok := v.(string)
if !ok {
return fmt.Errorf(
"nic: basic-auth %v[%T] must be string type",
v, v)
}
req.SetBasicAuth(k, vs)
}
}
if h.Files != nil {
err := setFiles(req, h.Files, h.Chunked)
if err != nil {
return err
}
}
if h.JSON != nil {
err := setJSON(req, h.JSON, h.Chunked)
if err != nil {
return err
}
}
return nil
}
// set option for http.Client
// proxy, timeout, redirect
func (h H) setClientOpt(client *http.Client) error {
if !h.AllowRedirect {
client.CheckRedirect = disableRedirect
}
client.Timeout = time.Duration(h.Timeout) * time.Second
transport := client.Transport.(*http.Transport)
transport.DisableKeepAlives = h.DisableKeepAlives
transport.DisableCompression = h.DisableCompression
if h.SkipVerifyTLS {
if transport.TLSClientConfig == nil {
transport.TLSClientConfig = &tls.Config{}
}
transport.TLSClientConfig.InsecureSkipVerify = true
}
if h.Proxy != "" {
urli := url.URL{}
urlproxy, err := urli.Parse(h.Proxy)
if err != nil {
return err
}
transport.Proxy = http.ProxyURL(urlproxy)
}
return nil
}