作者:hhxsv5 | 来源:互联网 | 2023-09-25 22:40
看到平台银行对接方案写的demo确实还不错记个笔记互相学习学习packageapiimport(cryptotlsnetnethttpstringssynct
看到平台银行对接方案
写的 demo 确实还不错
记个笔记 互相学习学习
package api
import (
"crypto/tls"
"net"
"net/http"
"strings"
"sync"
"time"
)
const (
defaultPoolSize = 50
defaultRequestTimeout = 30 * time.Second
defaultTLSShakeTimeout = 5 * time.Second
defaultConnectTimeout = 5 * time.Second
defaultKeepAliveTimeout = 15 * time.Second
)
var oneManager sync.Once
var connectManager *connectionManager
type connectionManager struct {
clientPool map[string]*http.Client
mapLock sync.RWMutex
}
func NewConnectionManager() *connectionManager {
oneManager.Do(func() {
if connectManager == nil {
connectManager = &connectionManager{clientPool: make(map[string]*http.Client)}
}
})
return connectManager
}
func (c *connectionManager) GetHttpClient(url string) *http.Client {
c.mapLock.RLock()
if _, ok := c.clientPool[url]; ok {
client := c.clientPool[url]
c.mapLock.RUnlock()
return client
}
c.mapLock.RUnlock()
innerContext := net.Dialer{
Timeout: defaultConnectTimeout,
KeepAlive: defaultKeepAliveTimeout}
transport := &http.Transport{
MaxIdleConnsPerHost: defaultPoolSize,
MaxConnsPerHost: defaultPoolSize,
DialContext: innerContext.DialContext}
if isHttps(url) {
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
transport.TLSHandshakeTimeout = defaultTLSShakeTimeout
}
tempClient := &http.Client{
Timeout: defaultRequestTimeout,
Transport: transport,
}
c.mapLock.Lock()
c.clientPool[url] = tempClient
c.mapLock.Unlock()
return tempClient
}
func isHttps(url string) bool {
urlArray := strings.Split(url, ":")
if urlArray[0] == "https" {
return true
}
return false
}