github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/http.go (about) 1 package utils 2 3 import ( 4 "crypto/tls" 5 "io" 6 "net/http" 7 "net/http/httputil" 8 "sync" 9 "time" 10 ) 11 12 // HTTP请求客户端管理 13 var timeoutClientMap = map[time.Duration]*http.Client{} // timeout => Client 14 var timeoutClientLocker = sync.Mutex{} 15 16 // DumpResponse 导出响应 17 func DumpResponse(resp *http.Response) (header []byte, body []byte, err error) { 18 header, err = httputil.DumpResponse(resp, false) 19 if err != nil { 20 return 21 } 22 body, err = io.ReadAll(resp.Body) 23 return 24 } 25 26 // NewHTTPClient 获取一个新的Client 27 func NewHTTPClient(timeout time.Duration) *http.Client { 28 return &http.Client{ 29 Timeout: timeout, 30 Transport: &http.Transport{ 31 MaxIdleConns: 4096, 32 MaxIdleConnsPerHost: 32, 33 MaxConnsPerHost: 32, 34 IdleConnTimeout: 2 * time.Minute, 35 ExpectContinueTimeout: 1 * time.Second, 36 TLSHandshakeTimeout: 10 * time.Second, 37 TLSClientConfig: &tls.Config{ 38 InsecureSkipVerify: true, 39 }, 40 }, 41 } 42 } 43 44 // SharedHttpClient 获取一个公用的Client 45 func SharedHttpClient(timeout time.Duration) *http.Client { 46 timeoutClientLocker.Lock() 47 defer timeoutClientLocker.Unlock() 48 49 client, ok := timeoutClientMap[timeout] 50 if ok { 51 return client 52 } 53 client = NewHTTPClient(timeout) 54 timeoutClientMap[timeout] = client 55 return client 56 }