-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
90 lines (79 loc) · 1.9 KB
/
http.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
package http_client
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"time"
)
const (
MaxIdleConns = 100
MaxIdleConnsPerHost = 100
IdleConnTimeout = 90 * time.Second
KeepAlive = 30 * time.Second
Timeout = 30 * time.Second
)
type Options struct {
MaxIdleConns int
MaxIdleConnsPerHost int
IdleConnTimeout time.Duration
Timeout time.Duration
KeepAlive time.Duration
}
type Client http.Client
func New(usePool bool, op Options) *Client {
var client = new(Client)
if usePool {
if op.MaxIdleConns == 0 {
op.MaxIdleConns = MaxIdleConns
}
if op.MaxIdleConnsPerHost == 0 {
op.MaxIdleConnsPerHost = MaxIdleConnsPerHost
}
if op.IdleConnTimeout == 0 {
op.IdleConnTimeout = IdleConnTimeout
}
if op.KeepAlive == 0 {
op.IdleConnTimeout = KeepAlive
}
if op.Timeout == 0 {
op.Timeout = Timeout
}
client.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: op.Timeout,
KeepAlive: op.KeepAlive,
}).DialContext,
MaxIdleConns: op.MaxIdleConns,
MaxIdleConnsPerHost: op.MaxIdleConnsPerHost,
IdleConnTimeout: op.IdleConnTimeout,
}
}
return client
}
func (c *Client) ReqJson(method string, url string, header http.Header,
InputData, outputData interface{}) (int, error) {
body, _ := json.Marshal(InputData)
req, err := http.NewRequest(method, url, bytes.NewReader(body))
if err != nil {
return 0, err
}
req.Header = header
response, err := (*http.Client)(c).Do(req)
if err != nil {
return 0, err
}
if response.StatusCode != http.StatusOK {
return response.StatusCode, fmt.Errorf("[%d] http request failed", response.StatusCode)
}
by, err := ioutil.ReadAll(response.Body)
if err != nil {
return http.StatusOK, err
}
err = json.Unmarshal(by, outputData)
response.Body.Close()
return http.StatusOK, err
}