看到平台银行对接方案
写的 demo 确实还不错
记个笔记 互相学习学习

package api

import (
        "crypto/tls"
        "net"
        "net/http"
        "strings"
        "sync"
        "time"
)

// http连接池相关参数
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
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
快乐就是解决一个又一个的问题!