From 39bc34e29196ec4128fad109df936a1ba559885f Mon Sep 17 00:00:00 2001 From: Phu Ngo <12547020+NgoKimPhu@users.noreply.github.com> Date: Tue, 9 Jan 2024 16:33:44 +0700 Subject: [PATCH] feat: add config for http transport - MaxIdleConns - MaxIdleConnsPerHost - MaxConnsPerHost --- http.go | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/http.go b/http.go index 729c30b..c581529 100644 --- a/http.go +++ b/http.go @@ -14,14 +14,17 @@ import ( // HttpCfg is the resty http client configs type HttpCfg struct { - HttpClient *http.Client `json:"-"` - BaseUrl string // client's base url for all methods - Headers http.Header // default headers - Timeout time.Duration // request timeout, see http.Client's Timeout - RetryCount int // retry count (exponential backoff), default 0 - RetryWaitTime time.Duration // first exponential backoff, default 100ms - RetryMaxWaitTime time.Duration // max exponential backoff, default 2s - Debug bool // whether to log requests and responses + HttpClient *http.Client `json:"-"` + BaseUrl string // client's base url for all methods + Headers http.Header // default headers + Timeout time.Duration // request timeout, see http.Client's Timeout + MaxIdleConns int // max idle connections for all hosts, default 100 + MaxIdleConnsPerHost int // max idle connections per host, default GOMAXPROCS+1 + MaxConnsPerHost int // max total connections per host, default 0 (unlimited) + RetryCount int // retry count (exponential backoff), default 0 + RetryWaitTime time.Duration // first exponential backoff, default 100ms + RetryMaxWaitTime time.Duration // max exponential backoff, default 2s + Debug bool // whether to log requests and responses } // NewRestyClient creates a new resty client with the given configs @@ -37,6 +40,19 @@ func (h *HttpCfg) NewRestyClient() (client *resty.Client) { hc.Timeout = h.Timeout } client = resty.NewWithClient(hc) + if transport, err := client.Transport(); err == nil && transport != nil { + transport = transport.Clone() + if h.MaxIdleConns != 0 { + transport.MaxIdleConns = h.MaxIdleConns + } + if h.MaxIdleConnsPerHost != 0 { + transport.MaxIdleConnsPerHost = h.MaxIdleConnsPerHost + } + if h.MaxConnsPerHost != 0 { + transport.MaxConnsPerHost = h.MaxConnsPerHost + } + client.SetTransport(transport) + } client.SetBaseURL(h.BaseUrl). SetRetryCount(h.RetryCount).