-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhttputil.go
69 lines (64 loc) · 1.95 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
package tableau4go
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"time"
)
var (
connectTimeOut = time.Duration(10 * time.Second)
readWriteTimeout = time.Duration(20 * time.Second)
)
func timeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err 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 {
conn.SetDeadline(time.Now().Add(rwTimeout))
}
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 := &tls.Config{InsecureSkipVerify: true}
if useClientCerts && len(certLocation) > 0 && len(keyLocation) > 0 {
// Load client cert if available
cert, err := tls.LoadX509KeyPair(certLocation, keyLocation)
if err == 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)
tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true, RootCAs: caCertPool}
tlsConfig.BuildNameToCertificate()
} else {
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)
}