-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
120 lines (97 loc) · 2.02 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
package gclient
import (
"context"
"github.com/jianzhiyao/gclient/request"
"github.com/jianzhiyao/gclient/response"
"io"
"net/http"
"time"
)
type Sign int8
const (
SignGzip Sign = 1 << 0
SignBr Sign = 1 << 1
)
type Client struct {
ctx context.Context
retry int
//Client level headers
headers http.Header
clientCookieJar http.CookieJar
clientTransport http.RoundTripper
clientCheckRedirect CheckRedirectHandler
clientTimeout time.Duration
sign int8
}
func New(options ...Option) *Client {
c := &Client{
headers: http.Header{},
}
c.Options(options...)
return c
}
func (r *Client) Option(option Option) *Client {
option(r)
return r
}
func (r *Client) Close() {
}
func (r *Client) Options(options ...Option) *Client {
for _, option := range options {
r.Option(option)
}
return r
}
func (r *Client) newHttpClient() (c *http.Client, returnBack ReturnHttpClient) {
c, returnBack = getClientFromPool()
c.Transport = r.clientTransport
c.CheckRedirect = r.clientCheckRedirect
c.Jar = r.clientCookieJar
c.Timeout = r.clientTimeout
return
}
func (r *Client) Do(method, url string) (*response.Response, error) {
return r.do(method, url, nil, nil)
}
func (r *Client) DoRequest(req *request.Request) (resp *response.Response, err error) {
return r.do(
req.GetMethod(),
req.GetUrl(),
req.GetBody(),
req.GetHeaders(),
)
}
func (r *Client) do(method, url string, body io.Reader, headers http.Header) (*response.Response, error) {
var (
resp *http.Response
err error
)
c, returnBack := r.newHttpClient()
defer returnBack(c)
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
//set request headers
//header from client
req.Header = r.headers.Clone()
//header from request
for key, header := range headers {
req.Header[key] = header
}
tryCount := r.retry
if tryCount <= 1 {
tryCount = 1
}
for tryCount > 0 {
resp, err = c.Do(req)
if err != nil {
break
}
tryCount--
}
if err != nil {
return nil, err
}
return response.New(resp)
}