-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
110 lines (93 loc) · 1.92 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
package h3
import (
"io"
"net/http"
"net/url"
"time"
)
type Client struct {
BaseURL string
BaseHeader http.Header
BaseParams url.Values
client *http.Client
onBefore func(req *http.Request) error
onAfter func(res *Response) error
enableDump bool
}
func New() *Client {
return &Client{
BaseHeader: make(http.Header),
BaseParams: make(url.Values),
client: &http.Client{},
}
}
func (c *Client) SetTransport(transport http.RoundTripper) {
c.client.Transport = transport
}
func (c *Client) SetTimeout(timeout time.Duration) {
c.client.Timeout = timeout
}
func (c *Client) SetJar(jar http.CookieJar) {
c.client.Jar = jar
}
func (c *Client) SetDump(enable bool) {
c.enableDump = enable
}
func (c *Client) OnBefore(fn func(req *http.Request) error) {
if fn == nil {
return
}
old := c.onBefore
c.onBefore = func(req *http.Request) error {
if old != nil {
if err := old(req); err != nil {
return err
}
}
return fn(req)
}
}
func (c *Client) OnAfter(fn func(res *Response) error) {
if fn == nil {
return
}
old := c.onAfter
c.onAfter = func(res *Response) error {
if old != nil {
if err := old(res); err != nil {
return err
}
}
return fn(res)
}
}
func (c *Client) Req(method string, path string) *Request {
req := NewRequest(method, path)
req.Client = c
req.Dump = c.enableDump
return req
}
func (c Client) Get(path string) *Request {
return c.Req("GET", path)
}
func (c Client) Post(path string, body io.Reader) *Request {
req := c.Req("POST", path)
req.Body = body
return req
}
func (c Client) Put(path string, body io.Reader) *Request {
req := c.Req("PUT", path)
req.Body = body
return req
}
func (c Client) Patch(path string, body io.Reader) *Request {
req := c.Req("PATCH", path)
req.Body = body
return req
}
func (c Client) Delete(path string) *Request {
return c.Req("DELETE", path)
}
func (c Client) Head(path string) *Request {
return c.Req("HEAD", path)
}