-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtarget_client.go
69 lines (52 loc) · 1.4 KB
/
target_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
package webhook
import (
"bytes"
"io/ioutil"
"net/http"
"time"
"crypto/tls"
"crypto/x509"
"fmt"
"github.com/hashicorp/errwrap"
)
func sendRequest(url string, body []byte, followRedirects bool, timeout time.Duration, cert []byte) ([]byte, error) {
var tlsConfig *tls.Config
if len(cert) != 0 {
rootCAs := x509.NewCertPool()
if !rootCAs.AppendCertsFromPEM(cert) {
return nil, fmt.Errorf("couldn't add target specific CA cert when trying to reach %q", url)
}
tlsConfig = &tls.Config{
InsecureSkipVerify: false,
RootCAs: rootCAs,
}
} else {
rootCAs, _ := x509.SystemCertPool()
tlsConfig = &tls.Config{
InsecureSkipVerify: false,
RootCAs: rootCAs,
}
}
tr := &http.Transport{TLSClientConfig: tlsConfig}
client := &http.Client{Transport: tr}
client.Timeout = timeout
if !followRedirects {
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
}
req, err := http.NewRequest("POST", url, bytes.NewReader(body))
if err != nil {
return nil, errwrap.Wrapf("error making request: {{err}}", err)
}
resp, err := client.Do(req)
if err != nil {
return nil, errwrap.Wrapf("error making request: {{err}}", err)
}
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errwrap.Wrapf("error reading response: {{err}}", err)
}
resp.Body.Close()
return responseBody, nil
}