-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
76 lines (67 loc) · 1.54 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
package hhttp
import (
"context"
"net/http"
"time"
)
type hiclient struct {
client *http.Client
opt Options
}
type RetryErrorFunc func(ctx context.Context, r *Request) error
type Header map[string][]string
var defaultTrimChars = string([]byte{
'\t', // Tab.
'\v', // Vertical tab.
'\n', // New line (line feed).
'\r', // Carriage return.
'\f', // New page.
' ', // Ordinary space.
0x00, // NUL-byte.
0x85, // Delete.
0xA0, // Non-breaking space.
})
var client = hiclient{
client: &http.Client{
Timeout: 30 * time.Second,
},
opt: Options{
retryCount: 0,
retryWait: time.Duration(0),
retryError: func(ctx context.Context, r *Request) error {
return nil
},
timeout: 5 * time.Second,
},
}
// Load 设置client的全局参数
func Load(opts ...Option) {
for _, o := range opts {
o(&client.opt)
}
}
// SetHeader 以k-v格式设置header
func (r *Request) SetHeader(key, value string) *Request {
r.header.Add(key, value)
return r
}
// SetHeaders 设置header参数 Header
// 例如: c.Headers(header)
func (r *Request) SetHeaders(headers Header) *Request {
for k, header := range headers {
for _, he := range header {
r.header.Add(k, he)
}
}
return r
}
// SetCookies 设置cookie
func (r *Request) SetCookies(hc ...*http.Cookie) *Request {
r.cookies = append(r.cookies, hc...)
return r
}
// SetTimeout 修改http.Client的超时时间,该超时时间默认是30s,优先级大于通过context设置的超时时间
func (r *Request) SetTimeout(t time.Duration) *Request {
r.client.client.Timeout = t
return r
}