Files
EdgeNode/internal/utils/http.go

57 lines
1.2 KiB
Go
Raw Normal View History

2020-09-26 08:07:07 +08:00
package utils
import (
"crypto/tls"
2022-08-04 11:34:06 +08:00
"io"
2020-09-26 08:07:07 +08:00
"net/http"
"net/http/httputil"
"sync"
"time"
)
// HTTP请求客户端管理
var timeoutClientMap = map[time.Duration]*http.Client{} // timeout => Client
var timeoutClientLocker = sync.Mutex{}
2021-12-18 19:17:40 +08:00
// DumpResponse 导出响应
2020-09-26 08:07:07 +08:00
func DumpResponse(resp *http.Response) (header []byte, body []byte, err error) {
header, err = httputil.DumpResponse(resp, false)
2021-08-07 16:27:42 +08:00
if err != nil {
return
}
2022-08-04 11:34:06 +08:00
body, err = io.ReadAll(resp.Body)
2020-09-26 08:07:07 +08:00
return
}
2021-12-18 19:17:40 +08:00
// NewHTTPClient 获取一个新的Client
2020-09-26 08:07:07 +08:00
func NewHTTPClient(timeout time.Duration) *http.Client {
return &http.Client{
Timeout: timeout,
Transport: &http.Transport{
MaxIdleConns: 4096,
MaxIdleConnsPerHost: 32,
MaxConnsPerHost: 32,
IdleConnTimeout: 2 * time.Minute,
ExpectContinueTimeout: 1 * time.Second,
2021-12-18 19:17:40 +08:00
TLSHandshakeTimeout: 10 * time.Second,
2020-09-26 08:07:07 +08:00
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
}
2021-12-18 19:17:40 +08:00
// SharedHttpClient 获取一个公用的Client
2020-09-26 08:07:07 +08:00
func SharedHttpClient(timeout time.Duration) *http.Client {
timeoutClientLocker.Lock()
defer timeoutClientLocker.Unlock()
client, ok := timeoutClientMap[timeout]
if ok {
return client
}
client = NewHTTPClient(timeout)
timeoutClientMap[timeout] = client
return client
}