-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallx.go
304 lines (252 loc) · 7.5 KB
/
callx.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
package callx
import (
"bufio"
"crypto/tls"
"github.com/goccy/go-json"
"github.com/valyala/fasthttp"
"io"
"net/http"
"time"
)
// Constant Header
const (
Authorization = "Authorization"
ContentType = "Content-Type"
Accept = "Accept"
Basic = "Basic"
Bearer = "Bearer"
)
// Header custom type
type Header map[string]string
// Body custom type
type Body map[string]any
// Form custom type
type Form io.Reader
// Custom callx request model
type Custom struct {
URL string
Method string
Header Header
Body interface{}
Form Form
}
// Config callx model
type Config struct {
BaseURL string
// Client name. Used in User-Agent request header.
//
// Default client name is used if not set.
Name string
// Maximum duration for full request writing and response reading (including body).
//
Timeout time.Duration
// Maximum duration for full response reading (including body).
//
// By default response read timeout is unlimited.
ReadTimeout time.Duration
// Maximum duration for full request writing (including body).
//
// By default request write timeout is unlimited.
WriteTimeout time.Duration
// Idle keep-alive connections are closed after this duration.
//
// By default idle connections are closed after DefaultMaxIdleConnDuration.
MaxIdleConnDuration time.Duration
Interceptor []Interceptor
// TLS config for https connections.
//
// Default TLS config is used if not set.
TLSConfig *tls.Config
// InsecureSkipVerify controls whether a client verifies the server's certificate chain and host name.
InsecureSkipVerify bool
// TCPDialer contains options to control a group of Dial calls.
TCPDialer *fasthttp.TCPDialer
// Maximum number of connections per each host which may be established.
//
// DefaultMaxConnsPerHost is used if not set.
MaxConnsPerHost int
// Per-connection buffer size for responses' reading.
// This also limits the maximum header size.
//
// Default buffer size is used if 0.
ReadBufferSize int
// Per-connection buffer size for requests' writing.
//
// Default buffer size is used if 0.
WriteBufferSize int
// RetryIf controls whether a retry should be attempted after an error.
//
// By default will use isIdempotent function.
RetryIf fasthttp.RetryIfFunc
// StreamResponseBody enables response body streaming.
StreamResponseBody bool
Cookies bool
}
// Interceptor the interface
type Interceptor interface {
Request(req *fasthttp.Request)
Response(res *fasthttp.Response)
}
// Response callx model
type Response struct {
Code int
Data []byte
Cookies map[string]string
}
// CallX the interface
type CallX interface {
Get(url string) Response
Post(url string, body interface{}) Response
Patch(url string, body interface{}) Response
Put(url string, body interface{}) Response
Delete(url string) Response
Req(custom Custom) Response
AddInterceptor(intercept ...Interceptor)
request(urlStr string, method string, header Header, payload interface{}) Response
}
type callxMethod struct {
Config *Config
Client *fasthttp.Client
}
func (n *callxMethod) Get(url string) Response {
return n.request(url, http.MethodGet, nil, nil)
}
func (n *callxMethod) Post(url string, body interface{}) Response {
return n.request(url, http.MethodPost, nil, body)
}
func (n *callxMethod) Patch(url string, body interface{}) Response {
return n.request(url, http.MethodPatch, nil, body)
}
func (n *callxMethod) Put(url string, body interface{}) Response {
return n.request(url, http.MethodPut, nil, body)
}
func (n *callxMethod) Delete(url string) Response {
return n.request(url, http.MethodDelete, nil, nil)
}
func (n *callxMethod) Req(custom Custom) Response {
if custom.Form != nil {
return n.request(custom.URL, custom.Method, custom.Header, custom.Form)
}
return n.request(custom.URL, custom.Method, custom.Header, custom.Body)
}
func (n *callxMethod) AddInterceptor(intercept ...Interceptor) {
for _, ins := range intercept {
n.Config.Interceptor = append(n.Config.Interceptor, ins)
}
}
func (n *callxMethod) request(urlStr string, method string, header Header, payload interface{}) Response {
req := fasthttp.AcquireRequest()
resp := fasthttp.AcquireResponse()
defer func() {
fasthttp.ReleaseRequest(req)
fasthttp.ReleaseResponse(resp)
}()
endpointURL := urlStr
if n.Config.BaseURL != "" {
endpointURL = n.Config.BaseURL + urlStr
}
req.SetRequestURI(endpointURL)
req.Header.SetMethod(method)
setRequestInterceptor(req, n.Config.Interceptor)
setHeaders(req, header)
if payload != nil {
if form, fok := payload.(Form); fok {
req.SetBodyStreamWriter(func(w *bufio.Writer) {
defer func(w *bufio.Writer) {
_ = w.Flush()
}(w)
_, _ = w.ReadFrom(form)
})
} else {
if data, e := json.Marshal(payload); e == nil {
req.SetBodyRaw(data)
}
}
}
err := n.Client.Do(req, resp)
if err != nil {
return Response{
Code: http.StatusNotFound,
Data: []byte(err.Error()),
}
}
setResponseInterceptor(resp, n.Config.Interceptor)
if n.Config.Cookies {
cookies := map[string]string{}
resp.Header.VisitAllCookie(func(key, value []byte) {
cookies[string(key)] = string(value)
})
return Response{Code: resp.StatusCode(), Data: resp.Body(), Cookies: cookies}
}
return Response{Code: resp.StatusCode(), Data: resp.Body()}
}
func setRequestInterceptor(req *fasthttp.Request, interceptors []Interceptor) {
for _, interceptor := range interceptors {
interceptor.Request(req)
}
}
func setResponseInterceptor(res *fasthttp.Response, interceptors []Interceptor) {
for _, interceptor := range interceptors {
interceptor.Response(res)
}
}
func setHeaders(req *fasthttp.Request, header Header) {
if header != nil {
for k, v := range header {
req.Header.Set(k, v)
}
}
}
// New callx
func New(config Config) CallX {
// increase DNS cache time to an hour instead of default minute
tcpDialer := &fasthttp.TCPDialer{
Concurrency: 4096,
DNSCacheDuration: time.Hour,
}
if config.TCPDialer != nil {
tcpDialer = config.TCPDialer
}
client := &fasthttp.Client{
Name: config.Name,
ReadTimeout: time.Second * 30,
WriteTimeout: time.Second * 30,
NoDefaultUserAgentHeader: true, // Don't send: User-Agent: fasthttp
DisableHeaderNamesNormalizing: true, // If you set the case on your headers correctly you can enable this
DisablePathNormalizing: true,
MaxIdleConnDuration: time.Hour * 1,
Dial: tcpDialer.Dial,
ReadBufferSize: config.ReadBufferSize,
WriteBufferSize: config.WriteBufferSize,
RetryIf: config.RetryIf,
StreamResponseBody: config.StreamResponseBody,
}
if config.MaxConnsPerHost > 0 {
client.MaxConnsPerHost = config.MaxConnsPerHost
}
if config.MaxIdleConnDuration > 0 {
client.MaxIdleConnDuration = config.MaxIdleConnDuration
}
if config.Timeout > 0 {
client.ReadTimeout = time.Second * config.Timeout
client.WriteTimeout = time.Second * config.Timeout
} else {
if config.ReadTimeout > 0 {
client.ReadTimeout = time.Second * config.ReadTimeout
config.Timeout = time.Second * config.ReadTimeout
}
if config.WriteTimeout > 0 {
client.WriteTimeout = time.Second * config.WriteTimeout
config.Timeout = time.Second * config.WriteTimeout
}
if config.TLSConfig != nil {
client.TLSConfig = config.TLSConfig
} else if config.InsecureSkipVerify {
client.TLSConfig = &tls.Config{InsecureSkipVerify: config.InsecureSkipVerify}
}
}
return &callxMethod{
Config: &config,
Client: client,
}
}