diff --git a/README.md b/README.md index 3763a36..96a1835 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/http.go b/http.go index 5fd7a12..99a9bb1 100644 --- a/http.go +++ b/http.go @@ -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). @@ -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 } @@ -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()