Skip to content

Commit

Permalink
Merge branch 'phu/http-timeout'
Browse files Browse the repository at this point in the history
  • Loading branch information
NgoKimPhu committed Dec 29, 2023
2 parents 85a7ed5 + 487c097 commit c987bc6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
### Why

Reusable util code
Reusable Kyber utilities

### What

- ctx.go: Context that ignores being cancelled
- http.go: Resty HTTP client with easy configs
- map.go: Collects values from a slice
- num.go: Conversions, Min, Max, Abs
- slice.go: Checks for existence, maps with fn, gets unique elements, filters
- string.go: String utils
28 changes: 20 additions & 8 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,31 @@ import (
"github.com/hashicorp/go-retryablehttp"
)

// 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
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
}

// NewRestyClient creates a new resty client with the given configs
func (h *HttpCfg) NewRestyClient() (client *resty.Client) {
if h == nil {
return resty.New()
}
if hc := h.HttpClient; hc == nil {
client = resty.New()
} else {
client = resty.NewWithClient(hc)

hc := h.HttpClient
if hc == nil {
hc = &http.Client{Timeout: h.Timeout}
} else if hc.Timeout == 0 {
hc.Timeout = h.Timeout
}
client = resty.NewWithClient(hc)

client.SetBaseURL(h.BaseUrl).
SetRetryCount(h.RetryCount).
Expand All @@ -43,7 +49,7 @@ func (h *HttpCfg) NewRestyClient() (client *resty.Client) {
if maxWaitTime := h.RetryMaxWaitTime; maxWaitTime != 0 {
client.SetRetryMaxWaitTime(maxWaitTime)
}
client.JSONMarshal = json.Marshal
client.JSONMarshal = JSONMarshal
client.JSONUnmarshal = JSONUnmarshal
return client
}
Expand All @@ -61,6 +67,12 @@ func retryableHttpError(r *resty.Response, err error) bool {
}
}

// JSONMarshal allows choosing the JSON marshalling implementation with build tag with the same logic as used by gin
func JSONMarshal(v any) ([]byte, error) {
return json.Marshal(v)
}

// JSONUnmarshal allows choosing the JSON unmarshalling implementation with build tag with the same logic as used by gin
func JSONUnmarshal(data []byte, v any) error {
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.UseNumber()
Expand Down

0 comments on commit c987bc6

Please sign in to comment.