forked from mattbaird/tableau4go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httputil.go
81 lines (70 loc) · 2.31 KB
/
httputil.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
package tableau4go
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"time"
)
var (
connectTimeOut = 10 * time.Second
readWriteTimeout = 20 * time.Second
)
func timeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(network, address string) (net.Conn, error) {
return func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, cTimeout)
if err != nil {
return nil, err
}
if rwTimeout > 0 {
if err = conn.SetDeadline(time.Now().Add(rwTimeout)); err != nil {
return nil, err
}
}
return conn, nil
}
}
// apps will set two OS variables:
// atscale_http_sslcert - location of the http ssl cert
// atscale_http_sslkey - location of the http ssl key
func NewTimeoutClient(cTimeout time.Duration, rwTimeout time.Duration, useClientCerts bool) *http.Client {
certLocation := os.Getenv("atscale_http_sslcert")
keyLocation := os.Getenv("atscale_http_sslkey")
caFile := os.Getenv("atscale_ca_file")
// default tlsConfig
//nolint:gosec // skip verify is currently allowed
tlsConfig := &tls.Config{InsecureSkipVerify: true}
//nolint:nestif // TODO: simplify nested if's
if useClientCerts && len(certLocation) > 0 && len(keyLocation) > 0 {
// Load client cert if available
if cert, loadKeyPairErr := tls.LoadX509KeyPair(certLocation, keyLocation); loadKeyPairErr == nil {
if len(caFile) > 0 {
caCertPool := x509.NewCertPool()
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
fmt.Printf("Error setting up caFile [%s]:%v\n", caFile, err)
}
caCertPool.AppendCertsFromPEM(caCert)
//nolint:gosec // skip verify is currently allowed
tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true, RootCAs: caCertPool}
//nolint:staticcheck // SA1019 TODO: remove this line and let go negotiate the first matching cert
tlsConfig.BuildNameToCertificate()
} else {
//nolint:gosec // skip verify is currently allowed
tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
}
}
}
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
Dial: timeoutDialer(cTimeout, rwTimeout),
},
}
}
func DefaultTimeoutClient() *http.Client {
return NewTimeoutClient(connectTimeOut, readWriteTimeout, false)
}