-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
90 lines (71 loc) · 2.16 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
package gofast
import (
"fmt"
"github.com/valyala/fasthttp"
)
type Header map[string]string
type Body map[string]string
type Client struct {
fastClient *fasthttp.Client
errorHandler ErrorHandler
requestEncoder RequestEncoder
responseDecoder ResponseDecoder
}
func New(config ...Config) *Client {
cfg := configDefault(config...)
return &Client{
fastClient: &fasthttp.Client{
Name: cfg.Name,
NoDefaultUserAgentHeader: cfg.NoDefaultUserAgentHeader,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
},
errorHandler: cfg.ErrorHandler,
requestEncoder: cfg.RequestEncoder,
responseDecoder: cfg.ResponseDecoder,
}
}
func (c *Client) Get(uri string, out interface{}, header Header) error {
return c.do(uri, fasthttp.MethodGet, nil, out, header)
}
func (c *Client) Post(uri string, in, out interface{}, header Header) error {
return c.do(uri, fasthttp.MethodPost, in, out, header)
}
func (c *Client) Put(uri string, in, out interface{}, header Header) error {
return c.do(uri, fasthttp.MethodPut, in, out, header)
}
func (c *Client) Patch(uri string, in, out interface{}, header Header) error {
return c.do(uri, fasthttp.MethodPatch, in, out, header)
}
func (c *Client) Delete(uri string, in, out interface{}, header Header) error {
return c.do(uri, fasthttp.MethodDelete, in, out, header)
}
func (c *Client) do(uri string, method string, in, out interface{}, header Header) error {
req, resp := fasthttp.AcquireRequest(), fasthttp.AcquireResponse()
defer func() {
fasthttp.ReleaseRequest(req)
fasthttp.ReleaseResponse(resp)
}()
req.SetRequestURI(uri)
req.Header.SetMethod(method)
for k, v := range header {
req.Header.Set(k, v)
}
if in != nil {
if err := c.requestEncoder(req, in); err != nil {
return fmt.Errorf("encode request: %w", err)
}
}
if err := c.fastClient.Do(req, resp); err != nil {
return fmt.Errorf("send request: %w", err)
}
if resp.StatusCode() < 200 || resp.StatusCode() > 299 {
return c.errorHandler(resp)
}
if out != nil {
if err := c.responseDecoder(resp, out); err != nil {
return fmt.Errorf("decode response: %w", err)
}
}
return nil
}