Skip to content

Commit

Permalink
feat: add config for http transport
Browse files Browse the repository at this point in the history
- MaxIdleConns
- MaxIdleConnsPerHost
- MaxConnsPerHost
  • Loading branch information
NgoKimPhu committed Jan 9, 2024
1 parent 5060f56 commit 39bc34e
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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).
Expand Down

0 comments on commit 39bc34e

Please sign in to comment.