-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
403 lines (339 loc) · 8.1 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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
package src
import (
"bytes"
"crypto/tls"
"errors"
"flag"
"fmt"
"io"
"mime/multipart"
"net/url"
"os"
"path"
"strings"
"sync"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpproxy"
)
var (
defaultTimeDuration = time.Second * 10
defaultContentType = "application/x-www-form-urlencoded"
jsonContentType = "application/json"
formContentType = "multipart/form-data"
EmptyUrlErr = errors.New("empty url")
EmptyFileErr = errors.New("empty file")
json = jsoniter.ConfigCompatibleWithStandardLibrary
)
type Client struct {
proxy string // set to all requests
timeout time.Duration
crt *tls.Certificate
opts *requestOptions
}
func NewClientPool() sync.Pool {
return sync.Pool{
New: func() interface{} {
return &Client{
timeout: defaultTimeDuration,
crt: nil,
opts: newRequestOptions(),
}
},
}
}
func NewClient() *Client {
return &Client{
timeout: defaultTimeDuration,
crt: nil,
opts: newRequestOptions(),
}
}
func (c *Client) SetProxy(proxy string) *Client {
c.proxy = proxy
return c
}
func (c *Client) SetTimeout(duration time.Duration) *Client {
c.timeout = duration
return c
}
func (c *Client) SetCrt(certPath, keyPath string) *Client {
clientCrt, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
// todo handle this err
clientCrt = tls.Certificate{}
}
c.crt = &clientCrt
return c
}
func (c *Client) AddParam(key, value string) *Client {
c.opts.params.Set(key, value)
return c
}
func (c *Client) AddParams(params Mapper) *Client {
for key, value := range params {
c.opts.params.Set(key, value)
}
return c
}
func (c *Client) AddHeader(key, value string) *Client {
c.opts.headers.normal.Set(key, value)
return c
}
func (c *Client) AddHeaders(headers Mapper) *Client {
for key, value := range headers {
c.opts.headers.normal.Set(key, value)
}
return c
}
func (c *Client) AddCookie(key, value string) *Client {
c.opts.headers.cookies.Set(key, value)
return c
}
func (c *Client) AddCookies(cookies Mapper) *Client {
for key, value := range cookies {
c.opts.headers.cookies.Set(key, value)
}
return c
}
func (c *Client) AddFile(fileName, filePath string) *Client {
c.opts.files.Set(fileName, filePath)
return c
}
func (c *Client) AddFiles(files Mapper) *Client {
for key, value := range files {
c.opts.files.Set(key, value)
}
return c
}
func (c *Client) AddBodyByte(body []byte) *Client {
c.opts.body = body
return c
}
func (c *Client) AddBodyStruct(object interface{}) *Client {
bodyByte, _ := json.Marshal(object)
c.opts.body = bodyByte
return c
}
func (c *Client) AddBodyBytes(bodyBytes []byte) *Client {
c.opts.body = bodyBytes
return c
}
func (c *Client) Get(rawUrl string) (*Response, error) {
if rawUrl == "" {
return nil, EmptyUrlErr
}
var (
urlValue = url.Values{}
err error
)
queryArray := strings.SplitN(rawUrl, "?", 2)
if len(queryArray) != 1 {
urlValue, err = url.ParseQuery(queryArray[1])
if err != nil {
return nil, err
}
}
for key, value := range c.opts.params.Mapper {
urlValue.Set(key, value)
}
reqUrl := addString(queryArray[0], "?", urlValue.Encode())
return c.call(reqUrl, fasthttp.MethodGet, c.opts.headers, nil)
}
func (c *Client) Post(url string) (*Response, error) {
if url == "" {
return nil, EmptyUrlErr
}
return c.call(url, fasthttp.MethodPost, c.opts.headers, c.opts.body)
}
func (c *Client) Put(url string) (*Response, error) {
if url == "" {
return nil, EmptyUrlErr
}
return c.call(url, fasthttp.MethodPut, c.opts.headers, c.opts.body)
}
func (c *Client) Delete(url string) (*Response, error) {
if url == "" {
return nil, EmptyUrlErr
}
return c.call(url, fasthttp.MethodDelete, c.opts.headers, c.opts.body)
}
func (c *Client) Options(url string) (*Response, error) {
if url == "" {
return nil, EmptyUrlErr
}
return c.call(url, fasthttp.MethodOptions, c.opts.headers, c.opts.body)
}
func (c *Client) SendFile(url string, options ...RequestOption) (*Response, error) {
if url == "" {
return nil, EmptyUrlErr
}
if len(c.opts.files.Mapper) == 0 {
return nil, EmptyFileErr
}
bodyBuffer := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuffer)
for fileName, filePath := range c.opts.files.Mapper {
fileWriter, err := bodyWriter.CreateFormFile(fileName, path.Base(filePath))
if err != nil {
return nil, err
}
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
_, err = io.Copy(fileWriter, file)
if err != nil {
_ = file.Close()
return nil, err
}
_ = file.Close()
}
_ = bodyWriter.Close()
c.opts.headers.normal.Set("content-type", bodyWriter.FormDataContentType())
return c.call(url, fasthttp.MethodPost, c.opts.headers, bodyBuffer.Bytes())
}
func (c *Client) call(url, method string, headers requestHeaders, body []byte) (*Response, error) {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
req.SetRequestURI(url)
req.Header.SetMethod(method)
for key, value := range headers.cookies.Mapper {
req.Header.SetCookie(key, value)
}
for key, value := range headers.normal.Mapper {
req.Header.Set(key, value)
}
if !req.Header.IsGet() {
contentType := string(req.Header.ContentType())
switch contentType {
case jsonContentType:
if body != nil {
req.SetBody(body)
}
default:
if !strings.Contains(contentType, formContentType) && body != nil {
argsMap := make(map[string]interface{})
if err := json.Unmarshal(body, &argsMap); err != nil {
return nil, err
}
fastArgs := new(fasthttp.Args)
for key, value := range argsMap {
fastArgs.Add(key, fmt.Sprintf("%v", value))
}
req.SetBody(fastArgs.QueryString())
} else {
req.SetBody(body)
}
}
}
client := &fasthttp.Client{
ReadTimeout: c.timeout,
}
if c.crt != nil {
client.TLSConfig = &tls.Config{
InsecureSkipVerify: true,
Certificates: []tls.Certificate{*c.crt},
}
}
if c.proxy != "" {
client.Dial = fasthttpproxy.FasthttpHTTPDialer(c.proxy)
}
if err := client.Do(req, resp); err != nil {
return nil, err
}
ret := &Response{
Cookie: RequestCookies{Mapper: NewCookies()},
Header: RequestHeaders{Mapper: NewHeaders()},
StatusCode: resp.StatusCode(),
Body: resp.Body(),
}
resp.Header.VisitAll(func(key, value []byte) {
ret.Header.Set(string(key), string(value))
})
resp.Header.VisitAllCookie(func(key, value []byte) {
ret.Cookie.Set(string(key), string(value))
})
return ret, nil
}
type Response struct {
StatusCode int
Body []byte
Header RequestHeaders
Cookie RequestCookies
}
func addString(ss ...string) string {
b := strings.Builder{}
for _, s := range ss {
b.WriteString(s)
}
return b.String()
}
type (
Mapper map[string]string
RequestParams struct{ Mapper }
RequestHeaders struct{ Mapper }
RequestCookies struct{ Mapper }
RequestFiles struct{ Mapper }
)
func NewParams() Mapper {
return make(map[string]string)
}
func NewHeaders() Mapper {
return make(map[string]string)
}
func NewCookies() Mapper {
return make(map[string]string)
}
func NewFiles() Mapper {
return make(map[string]string)
}
func (m Mapper) Get(key string) string {
value, ok := m[key]
if ok {
return value
}
return ""
}
func (m Mapper) Set(key, value string) Mapper {
m[key] = value
return m
}
func newRequestOptions() *requestOptions {
return &requestOptions{
files: RequestFiles{Mapper: NewFiles()},
headers: requestHeaders{
normal: RequestHeaders{Mapper: NewHeaders()},
cookies: RequestCookies{Mapper: NewCookies()},
},
params: RequestParams{Mapper: NewParams()},
}
}
type requestOptions struct {
body []byte
Proxy string
files RequestFiles
headers requestHeaders
params RequestParams
}
type requestHeaders struct {
normal RequestHeaders
cookies RequestCookies
}
type RequestOption struct {
f func(*requestOptions)
}
func main2() {
flag.Parse()
res, err := NewClient().
AddParam("param1", "param1").
AddHeader("header1", "header1").
AddCookie("cookie1", "cookie1").
Get("https://example.com")
if err == nil {
fmt.Println(string(res.Body))
}
}