Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add config for http transport #4

Merged
merged 1 commit into from
Jan 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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