github.com/chanxuehong/wechat@v0.0.0-20230222024006-36f0325263cd/mch/core/ssl_http_client_go1.8.go (about) 1 //go:build go1.8 2 // +build go1.8 3 4 package core 5 6 import ( 7 "crypto/tls" 8 "net" 9 "net/http" 10 "time" 11 ) 12 13 // NewTLSHttpClient 创建支持双向证书认证的 http.Client. 14 func NewTLSHttpClient(certFile, keyFile string) (httpClient *http.Client, err error) { 15 cert, err := tls.LoadX509KeyPair(certFile, keyFile) 16 if err != nil { 17 return nil, err 18 } 19 tlsConfig := &tls.Config{ 20 Certificates: []tls.Certificate{cert}, 21 } 22 return newTLSHttpClient(tlsConfig) 23 } 24 25 // NewTLSHttpClient2 创建支持双向证书认证的 http.Client. 26 func NewTLSHttpClient2(certPEMBlock, keyPEMBlock []byte) (httpClient *http.Client, err error) { 27 cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) 28 if err != nil { 29 return nil, err 30 } 31 tlsConfig := &tls.Config{ 32 Certificates: []tls.Certificate{cert}, 33 } 34 return newTLSHttpClient(tlsConfig) 35 } 36 37 func newTLSHttpClient(tlsConfig *tls.Config) (*http.Client, error) { 38 dialTLS := func(network, addr string) (net.Conn, error) { 39 return tls.DialWithDialer(&net.Dialer{ 40 Timeout: 5 * time.Second, 41 KeepAlive: 30 * time.Second, 42 }, network, addr, tlsConfig) 43 } 44 return &http.Client{ 45 Transport: &http.Transport{ 46 Proxy: http.ProxyFromEnvironment, 47 DialContext: (&net.Dialer{ 48 Timeout: 5 * time.Second, 49 KeepAlive: 30 * time.Second, 50 DualStack: true, 51 }).DialContext, 52 DialTLS: dialTLS, 53 MaxIdleConns: 100, 54 IdleConnTimeout: 90 * time.Second, 55 ExpectContinueTimeout: 1 * time.Second, 56 }, 57 }, nil 58 }