From a84e10bb8436f78c28316296b05dcdb79f322002 Mon Sep 17 00:00:00 2001 From: WJQSERVER Date: Thu, 23 Jan 2025 16:05:09 +0800 Subject: [PATCH] Add support for reusing the Go net/http Client. --- main.go | 6 +++--- proxy/chunkreq.go | 24 ++++++++++++++++++++++-- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 43b7e9c..4cd1968 100644 --- a/main.go +++ b/main.go @@ -91,8 +91,8 @@ func setupRateLimit(cfg *config.Config) { } } -func initBufferSize() { - proxy.InitChunkedBufferSize(cfg.Server.BufferSize) +func InitChunkedReq() { + proxy.InitChunkedReq(cfg.Server.BufferSize) } func init() { @@ -100,7 +100,7 @@ func init() { flag.Parse() loadConfig() setupLogger(cfg) - initBufferSize() + InitChunkedReq() loadlist(cfg) setupRateLimit(cfg) diff --git a/proxy/chunkreq.go b/proxy/chunkreq.go index d45229c..29bb4b5 100644 --- a/proxy/chunkreq.go +++ b/proxy/chunkreq.go @@ -6,13 +6,24 @@ import ( "ghproxy/config" "io" "net/http" + "time" "github.com/gin-gonic/gin" ) var chunkedBufferSize int -func InitChunkedBufferSize(cfgBufferSize int) { +var ( + client *http.Client + tr *http.Transport +) + +func InitChunkedReq(cfgBufferSize int) { + initChunkedBufferSize(cfgBufferSize) + initChunkedHTTPClient() +} + +func initChunkedBufferSize(cfgBufferSize int) { if cfgBufferSize == 0 { chunkedBufferSize = 4096 // 默认缓冲区大小 } else { @@ -20,12 +31,20 @@ func InitChunkedBufferSize(cfgBufferSize int) { } } +func initChunkedHTTPClient() { + tr = &http.Transport{ + MaxIdleConns: 100, + IdleConnTimeout: 30 * time.Second, + } + client = &http.Client{Transport: tr} +} + func ChunkedProxyRequest(c *gin.Context, u string, cfg *config.Config, mode string, runMode string) { method := c.Request.Method logInfo("%s %s %s %s %s", c.ClientIP(), method, u, c.Request.Header.Get("User-Agent"), c.Request.Proto) // 创建HTTP客户端 - client := &http.Client{} + //client := &http.Client{} // 发送HEAD请求, 预获取Content-Length headReq, err := http.NewRequest("HEAD", u, nil) @@ -84,6 +103,7 @@ func ChunkedProxyRequest(c *gin.Context, u string, cfg *config.Config, mode stri CopyResponseHeaders(resp, c, cfg) c.Status(resp.StatusCode) + if err := chunkedCopyResponseBody(c, resp.Body); err != nil { logError("%s %s %s %s %s 响应复制错误: %v", c.ClientIP(), method, u, c.Request.Header.Get("User-Agent"), c.Request.Proto, err) }