-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxhttp.go
More file actions
305 lines (264 loc) · 6.41 KB
/
Copy pathxhttp.go
File metadata and controls
305 lines (264 loc) · 6.41 KB
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package xhttp
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/buger/jsonparser"
)
const (
defaultConnTimeout = 3000
defaultRespTimeout = 5000
defaultTotalTimeout = 30000
minHttpUrlLen = len("http://")
ErrorDefault = -iota - 1 //-1
ErrorInvalidUrl
ErrorInvalidMethod
)
var (
errMsg = map[int]error{
ErrorDefault: errors.New("default error"),
ErrorInvalidUrl: errors.New("invalid url, lost http/https?"),
ErrorInvalidMethod: errors.New("invalid method"),
}
)
var allowMethods = map[string]bool{
http.MethodGet: true,
http.MethodPost: true,
http.MethodHead: true,
http.MethodPut: true,
http.MethodDelete: true,
http.MethodOptions: true,
}
type XHttp struct {
body string
method string
client *http.Client
params map[string]string
headers map[string]string
connectTimeout int64
responseHeaderTimeout int64
totalTimeout int64
}
// set the http method
func (c *XHttp) Method(m string) *XHttp {
c.method = m
return c
}
// set the http method to get
func (c *XHttp) Get() *XHttp {
c.method = "GET"
return c
}
// set the http method to post
func (c *XHttp) Post() *XHttp {
c.method = "POST"
return c
}
// add a http header
func (c *XHttp) AddHeader(k, v string) *XHttp {
if c.headers == nil {
c.headers = make(map[string]string)
}
c.headers[k] = v
return c
}
// add some http header
func (c *XHttp) AddHeaders(headerMap map[string]string) *XHttp {
if c.headers == nil {
c.headers = make(map[string]string)
}
for k, v := range headerMap {
c.headers[k] = v
}
return c
}
// set the http uri param
func (c *XHttp) AddParam(k, v string) *XHttp {
if c.params == nil {
c.params = make(map[string]string)
}
c.params[k] = v
return c
}
// add some http params
func (c *XHttp) AddParams(paramMap map[string]string) *XHttp {
if c.params == nil {
c.params = make(map[string]string)
}
for k, v := range paramMap {
c.params[k] = v
}
return c
}
// set the http body
func (c *XHttp) SetBody(b string) *XHttp {
c.body = b
return c
}
// set the http body by interface
// make sure marshal ok
func (c *XHttp) SetJsonBody(b interface{}) *XHttp {
body, _ := json.Marshal(b)
c.body = string(body)
return c
}
// New with default options
func New() *XHttp {
return NewWithOption(defaultConnTimeout, defaultRespTimeout, defaultTotalTimeout, "", true)
}
// NewWithOption
func NewWithOption(connectTimeout, responseHeaderTimeout, totalTimeout int64, proxy string, skipTLS bool) *XHttp {
dialTimeout := func(network, addr string) (net.Conn, error) {
dialer := &net.Dialer{
Timeout: time.Millisecond * time.Duration(connectTimeout),
}
conn, err := dialer.Dial(network, addr)
if err != nil {
err = fmt.Errorf("net.DialTimeout, addr:%s, err:%v", addr, err)
if conn != nil {
err = fmt.Errorf("%v, conn:%v", err, conn.RemoteAddr())
}
}
return conn, err
}
if proxy == "" {
return &XHttp{
connectTimeout: connectTimeout,
responseHeaderTimeout: responseHeaderTimeout,
totalTimeout: totalTimeout,
client: &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: dialTimeout,
ResponseHeaderTimeout: time.Millisecond * time.Duration(responseHeaderTimeout),
TLSClientConfig: &tls.Config{
InsecureSkipVerify: skipTLS,
},
},
Timeout: time.Millisecond * time.Duration(totalTimeout),
},
}
}
proxyURL, err := url.Parse(proxy)
if err != nil {
panic(err)
}
return &XHttp{
connectTimeout: connectTimeout,
responseHeaderTimeout: responseHeaderTimeout,
totalTimeout: totalTimeout,
client: &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
Dial: dialTimeout,
ResponseHeaderTimeout: time.Millisecond * time.Duration(responseHeaderTimeout),
TLSClientConfig: &tls.Config{
InsecureSkipVerify: skipTLS,
},
},
Timeout: time.Millisecond * time.Duration(totalTimeout),
},
}
}
// get all data from http request
func (c *XHttp) RespToString(url string) (string, error) {
resp, err := c.GetRestBody(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(data), nil
}
// get a json's value from http request
func (c *XHttp) RespGetJsonKey(url string, keys ...string) ([]byte, error) {
resp, err := c.GetRestBody(url)
if err != nil {
return []byte{}, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
v, _, _, err := jsonparser.Get(data, keys...)
return v, err
}
// get a http response body
// warning: you must close body at last
func (c *XHttp) GetRestBody(url string) (*http.Response, error) {
if len(url) <= minHttpUrlLen || url[0:4] != "http" {
return nil, errMsg[ErrorInvalidUrl]
}
if _, ok := allowMethods[c.method]; !ok {
return nil, errMsg[ErrorInvalidMethod]
}
req, err := http.NewRequest(c.method, url, strings.NewReader(c.body))
if err != nil {
return nil, err
}
q := req.URL.Query()
if c.params != nil {
for key, val := range c.params {
q.Add(key, val)
}
c.params = nil
req.URL.RawQuery = q.Encode()
}
// req.Header.Add will automatically capitalize the input characters.
if c.headers != nil {
header := req.Header
for k, v := range c.headers {
header[k] = []string{v}
}
c.headers = nil
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK &&
resp.StatusCode != http.StatusPartialContent {
return nil, errors.New(resp.Status)
}
return resp, nil
}
// get all data from http request
func (c *XHttp) RespToJson(url string, j interface{}) error {
resp, err := c.GetRestBody(url)
if err != nil {
return err
}
err = json.NewDecoder(resp.Body).Decode(j)
defer resp.Body.Close()
return err
}
// get all data from http request
func (c *XHttp) RespToJsonByKeys(url string, j interface{}, keys ...string) error {
resp, err := c.GetRestBody(url)
if err != nil {
return err
}
err = json.NewDecoder(resp.Body).Decode(j)
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
v, _, _, err := jsonparser.Get(data, keys...)
if err != nil {
return err
}
err = json.Unmarshal(v, j)
return err
}