-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequestoption.go
69 lines (55 loc) · 1.39 KB
/
requestoption.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
package httpclient
import (
"net/http"
"github.com/phamvinhdat/httpclient/body"
)
type requestOption struct {
bodyProvider body.Provider
header http.Header
query interface{}
hookFns []HookFn
}
type RequestOption interface {
apply(*requestOption)
}
func getRequestOption(opts ...RequestOption) requestOption {
opt := requestOption{
header: http.Header{},
}
for _, f := range opts {
f.apply(&opt)
}
return opt
}
type reqOptFunc func(*requestOption)
func (f reqOptFunc) apply(r *requestOption) {
f(r)
}
// WithHeader sets the header entries associated with key to the single
// element value. It replaces any existing values associated with key. If
// isAdding[0] == true (default is false) then It appends to any existing values
// associated with key
func WithHeader(key, value string, isAdding ...bool) RequestOption {
return reqOptFunc(func(r *requestOption) {
fn := r.header.Set
if isAdding != nil && isAdding[0] == true {
fn = r.header.Add
}
fn(key, value)
})
}
func WithBodyProvider(bProvider body.Provider) RequestOption {
return reqOptFunc(func(r *requestOption) {
r.bodyProvider = bProvider
})
}
func WithQuery(query interface{}) RequestOption {
return reqOptFunc(func(r *requestOption) {
r.query = query
})
}
func WithHookFn(hookFn HookFn) RequestOption {
return reqOptFunc(func(r *requestOption) {
r.hookFns = append(r.hookFns, hookFn)
})
}