/
client.go
136 lines (106 loc) · 2.5 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
package client
import (
"net/http"
"time"
"gopkg.in/ddo/go-dlog.v2"
"github.com/ddo/rq"
"github.com/ddo/rq/client/jar"
)
const (
defaultTimeout = 3 * time.Minute
defaultRedirects = 10
defaultUserAgent = "github.com/ddo/rq"
)
var log = dlog.New("rq:client", nil)
// Client contains stdlib http client and other custom client settings
type Client struct {
httpClient *http.Client
defaultRq *rq.Rq // default url, method, qs, form and headers if they are nil
}
// Option contains client settings
type Option struct {
Timeout time.Duration // if 0, default timeout will be applied
Jar *jar.Jar // if Jar is nil, there no cookie jar
Proxy string // Proxy option is the sugar syntax for Transport.Proxy
Transport http.RoundTripper
CheckRedirect func(req *http.Request, via []*http.Request) error
DefaultRq *rq.Rq
}
// New returns new client which init with provided options
func New(opt *Option) *Client {
if opt == nil {
opt = &Option{}
}
timeout := opt.Timeout
var jar http.CookieJar
proxy := opt.Proxy
transport := opt.Transport
checkRedirect := opt.CheckRedirect
defaultRq := opt.DefaultRq
if opt.Timeout == 0 {
timeout = defaultTimeout
}
if opt.Jar != nil {
jar = opt.Jar.GetHTTPJar()
}
if checkRedirect == nil {
checkRedirect = DefaultCheckRedirect
}
log.Info("timeout:", timeout)
log.Info("jar:", jar)
log.Info("proxy:", proxy)
log.Info("transport:", transport)
log.Info("checkRedirect:", checkRedirect)
client := &Client{
httpClient: &http.Client{
Timeout: timeout,
Jar: jar,
Transport: transport,
CheckRedirect: checkRedirect,
},
defaultRq: defaultRq,
}
if proxy != "" {
err := client.SetProxy(proxy)
if err != nil {
return nil
}
}
return client
}
// DefaultClient has default timeout and stdlib default transport
// no cookie management
var DefaultClient = New(nil)
// ApplyDefaultRq overrides Rq properties with default value if key is not set
func ApplyDefaultRq(defaultRq, _rq *rq.Rq) (newRq *rq.Rq) {
newRq = &rq.Rq{}
// copy
*newRq = *_rq
// return as is _rq if no defaultRq
if defaultRq == nil {
return
}
// url
if newRq.URL == "" {
newRq.URL = defaultRq.URL
}
// query
for k, v := range defaultRq.Query {
if _, ok := newRq.Query[k]; !ok {
newRq.Query[k] = v
}
}
// form
for k, v := range defaultRq.Form {
if _, ok := newRq.Form[k]; !ok {
newRq.Form[k] = v
}
}
// header
for k, v := range defaultRq.Header {
if _, ok := newRq.Header[k]; !ok {
newRq.Header[k] = v
}
}
return
}