-
Notifications
You must be signed in to change notification settings - Fork 24
/
requester.go
99 lines (87 loc) · 2.09 KB
/
requester.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
package icinga
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"io"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
)
func (ic *APIRequest) Do() *APIResponse {
if ic.Err != nil {
return &APIResponse{
Err: ic.Err,
}
}
ic.req.Header.Set("Accept", "application/json")
if ic.userName != "" && ic.password != "" {
ic.req.SetBasicAuth(ic.userName, ic.password)
}
ic.resp, ic.Err = ic.client.Do(ic.req)
if ic.Err != nil {
return &APIResponse{
Err: ic.Err,
}
}
ic.Status = ic.resp.StatusCode
ic.ResponseBody, ic.Err = ioutil.ReadAll(ic.resp.Body)
if ic.Err != nil {
return &APIResponse{
Err: ic.Err,
}
}
return &APIResponse{
Status: ic.Status,
ResponseBody: ic.ResponseBody,
}
}
func (r *APIResponse) Into(to interface{}) (int, error) {
if r.Err != nil {
return r.Status, r.Err
}
err := json.Unmarshal(r.ResponseBody, to)
if err != nil {
return r.Status, err
}
return r.Status, nil
}
func (c *Client) newRequest(path string) *APIRequest {
mTLSConfig := &tls.Config{}
if c.config.CACert != nil {
certs := x509.NewCertPool()
certs.AppendCertsFromPEM(c.config.CACert)
mTLSConfig.RootCAs = certs
} else {
mTLSConfig.InsecureSkipVerify = true
}
// ref: https://github.com/golang/go/blob/release-branch.go1.9/src/net/http/transport.go#L35
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: mTLSConfig,
}
client := &http.Client{Transport: tr}
return &APIRequest{
uri: c.config.Endpoint + path,
client: client,
userName: c.config.BasicAuth.Username,
password: c.config.BasicAuth.Password,
}
}
func (ic *APIRequest) newRequest(method, urlStr string, body io.Reader) (*http.Request, error) {
if strings.HasSuffix(urlStr, "/") {
urlStr = strings.TrimRight(urlStr, "/")
}
return http.NewRequest(method, urlStr, body)
}