-
Notifications
You must be signed in to change notification settings - Fork 698
/
ssl_http_client_go1.8.go
57 lines (52 loc) · 1.43 KB
/
ssl_http_client_go1.8.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
// +build go1.8
package core
import (
"crypto/tls"
"net"
"net/http"
"time"
)
// NewTLSHttpClient 创建支持双向证书认证的 http.Client.
func NewTLSHttpClient(certFile, keyFile string) (httpClient *http.Client, err error) {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
}
return newTLSHttpClient(tlsConfig)
}
// NewTLSHttpClient2 创建支持双向证书认证的 http.Client.
func NewTLSHttpClient2(certPEMBlock, keyPEMBlock []byte) (httpClient *http.Client, err error) {
cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
}
return newTLSHttpClient(tlsConfig)
}
func newTLSHttpClient(tlsConfig *tls.Config) (*http.Client, error) {
dialTLS := func(network, addr string) (net.Conn, error) {
return tls.DialWithDialer(&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 30 * time.Second,
}, network, addr, tlsConfig)
}
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
DialTLS: dialTLS,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}, nil
}