-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
106 lines (80 loc) · 1.69 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
package client
import (
http "github.com/valyala/fasthttp"
)
type Client struct {
Jar *Jar
config *Config
client *http.Client
}
type Config struct {
BaseURL string
Pre func(*http.Request)
Post func(*http.Response)
}
func New() *Client {
return &Client{
client: &http.Client{},
config: &Config{},
}
}
func NewWithConfig(config *Config) *Client {
if config == nil {
config = &Config{}
}
return &Client{
client: &http.Client{},
config: config,
}
}
func (c *Client) NewRequest(method string, url string, body []byte, options ...*Option) *http.Request {
req := http.AcquireRequest()
for _, opt := range options {
opt.Transform(req)
ReleaseOption(opt)
}
if c.Jar != nil {
c.Jar.mu.Lock()
for _, c := range c.Jar.cookies {
req.Header.SetCookieBytesKV(c.Key(), c.Value())
}
c.Jar.mu.Unlock()
}
if body != nil {
req.SetBody(body)
}
req.SetRequestURI(c.buildURL(url))
req.Header.SetMethod(method)
return req
}
func (c *Client) Do(req *http.Request) *http.Response {
if c.config.Pre != nil {
c.config.Pre(req)
}
resp := http.AcquireResponse()
defer http.ReleaseRequest(req)
c.client.Do(req, resp)
if c.Jar != nil {
c.Jar.mu.Lock()
resp.Header.VisitAllCookie(func(key, value []byte) {
cookie := http.AcquireCookie()
cookie.ParseBytes(value)
c.Jar.cookies[string(cookie.Key())] = cookie
})
c.Jar.mu.Unlock()
}
if c.config.Post != nil {
c.config.Post(resp)
}
return resp
}
func (c *Client) Get(url string) *http.Response {
req := c.NewRequest(http.MethodGet, url, nil)
return c.Do(req)
}
func (c *Client) buildURL(endpoint string) string {
if c.config == nil {
return endpoint
}
return c.config.BaseURL + endpoint
}