-
Notifications
You must be signed in to change notification settings - Fork 66
/
options.go
109 lines (87 loc) · 2.13 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
package xhttp
import (
"github.com/avast/retry-go"
"github.com/mix-go/xutil/xconv"
"net/http"
"time"
)
var DefaultOptions = newDefaultOptions()
func newDefaultOptions() RequestOptions {
return RequestOptions{
Header: http.Header{},
Timeout: time.Second * 5,
}
}
type RequestOptions struct {
Header http.Header
Body Body
// 默认: time.Second * 5
Timeout time.Duration
DebugFunc DebugFunc
// Retry
RetryIfFunc RetryIfFunc
RetryOptions []retry.Option
Middlewares []Middleware
}
func mergeOptions(opts []RequestOption) *RequestOptions {
cp := DefaultOptions // copy
for _, o := range opts {
o.apply(&cp)
}
return &cp
}
type RequestOption interface {
apply(*RequestOptions)
}
type funcRequestOption struct {
f func(*RequestOptions)
}
func (fdo *funcRequestOption) apply(do *RequestOptions) {
fdo.f(do)
}
func WithHeader(header http.Header) RequestOption {
return &funcRequestOption{func(opts *RequestOptions) {
opts.Header = header
}}
}
func WithContentType(contentType string) RequestOption {
return &funcRequestOption{func(opts *RequestOptions) {
opts.Header.Set("Content-Type", contentType)
}}
}
func WithTimeout(timeout time.Duration) RequestOption {
return &funcRequestOption{func(opts *RequestOptions) {
opts.Timeout = timeout
}}
}
func WithBody(body Body) RequestOption {
return &funcRequestOption{func(opts *RequestOptions) {
opts.Body = body
}}
}
func WithBodyBytes(body []byte) RequestOption {
return &funcRequestOption{func(opts *RequestOptions) {
opts.Body = body
}}
}
func WithBodyString(body string) RequestOption {
return &funcRequestOption{func(opts *RequestOptions) {
opts.Body = xconv.StringToBytes(body)
}}
}
func WithDebugFunc(f DebugFunc) RequestOption {
return &funcRequestOption{func(opts *RequestOptions) {
opts.DebugFunc = f
}}
}
func WithRetry(f RetryIfFunc, opts ...retry.Option) RequestOption {
return &funcRequestOption{func(o *RequestOptions) {
o.RetryIfFunc = f
o.RetryOptions = opts
}}
}
func WithMiddleware(middlewares ...Middleware) RequestOption {
return &funcRequestOption{func(o *RequestOptions) {
o.Middlewares = append(o.Middlewares, middlewares...)
}}
}