forked from xinliangnote/go-gin-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
121 lines (104 loc) · 2.32 KB
/
option.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
package httpclient
import (
"sync"
"time"
"github.com/imlida/go-gin-api/pkg/trace"
"go.uber.org/zap"
)
var (
cache = &sync.Pool{
New: func() interface{} {
return &option{
header: make(map[string][]string),
}
},
}
)
// Mock 定义接口Mock数据
type Mock func() (body []byte)
// Option 自定义设置http请求
type Option func(*option)
type option struct {
ttl time.Duration
header map[string][]string
trace *trace.Trace
dialog *trace.Dialog
logger *zap.Logger
retryTimes int
retryDelay time.Duration
retryVerify RetryVerify
alarmTitle string
alarmObject AlarmObject
alarmVerify AlarmVerify
mock Mock
}
func (o *option) reset() {
o.ttl = 0
o.header = make(map[string][]string)
o.trace = nil
o.dialog = nil
o.logger = nil
o.retryTimes = 0
o.retryDelay = 0
o.retryVerify = nil
o.alarmTitle = ""
o.alarmObject = nil
o.alarmVerify = nil
o.mock = nil
}
func getOption() *option {
return cache.Get().(*option)
}
func releaseOption(opt *option) {
opt.reset()
cache.Put(opt)
}
// WithTTL 本次http请求最长执行时间
func WithTTL(ttl time.Duration) Option {
return func(opt *option) {
opt.ttl = ttl
}
}
// WithHeader 设置http header,可以调用多次设置多对key-value
func WithHeader(key, value string) Option {
return func(opt *option) {
opt.header[key] = []string{value}
}
}
// WithTrace 设置trace信息
func WithTrace(t trace.T) Option {
return func(opt *option) {
if t != nil {
opt.trace = t.(*trace.Trace)
opt.dialog = new(trace.Dialog)
}
}
}
// WithLogger 设置logger以便打印关键日志
func WithLogger(logger *zap.Logger) Option {
return func(opt *option) {
opt.logger = logger
}
}
// WithMock 设置 mock 数据
func WithMock(m Mock) Option {
return func(opt *option) {
opt.mock = m
}
}
// WithOnFailedAlarm 设置告警通知
func WithOnFailedAlarm(alarmTitle string, alarmObject AlarmObject, alarmVerify AlarmVerify) Option {
return func(opt *option) {
opt.alarmTitle = alarmTitle
opt.alarmObject = alarmObject
opt.alarmVerify = alarmVerify
}
}
// WithOnFailedRetry 设置失败重试
func WithOnFailedRetry(retryTimes int, retryDelay time.Duration, retryVerify RetryVerify) Option {
return func(opt *option) {
opt.retryTimes = retryTimes
opt.retryDelay = retryDelay
opt.retryVerify = retryVerify
}
}