Documentation
¶
Overview ¶
Package httpclient provides a reusable, configurable HTTP client built on resty v3.
It offers sane defaults with an options pattern so every setting is overridable at creation time: retry policy, timeouts, base URL, default headers, transport, and middleware hooks.
Basic usage:
client := httpclient.New(
httpclient.WithBaseURL("https://api.example.com"),
httpclient.WithTimeout(10*time.Second),
)
resp, err := client.R(ctx).
SetHeader("Authorization", "Bearer ...").
SetBody(payload).
Post("/resource")
Index ¶
- Constants
- type Client
- type Option
- func WithAuthToken(token string) Option
- func WithBaseURL(url string) Option
- func WithBasicAuth(username, password string) Option
- func WithCookies(cookies ...*http.Cookie) Option
- func WithHeader(key, value string) Option
- func WithHeaders(headers map[string]string) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMethodDeleteAllowPayload(allow bool) Option
- func WithMethodGetAllowPayload(allow bool) Option
- func WithOpenTelemetry() Option
- func WithPathParam(name, value string) Option
- func WithQueryParam(name, value string) Option
- func WithRequestMiddleware(m resty.RequestMiddleware) Option
- func WithResponseMiddleware(m resty.ResponseMiddleware) Option
- func WithResponseSaveDirectory(dir string) Option
- func WithResponseSaveToFile(save bool) Option
- func WithRetryCondition(condition resty.RetryConditionFunc) Option
- func WithRetryCount(n int) Option
- func WithRetryHook(hook resty.RetryHookFunc) Option
- func WithRetryWaitTime(waitMin, waitMax time.Duration) Option
- func WithScheme(scheme string) Option
- func WithTimeout(d time.Duration) Option
- func WithTransport(transport http.RoundTripper) Option
Constants ¶
const DefaultRetryCount = 3
DefaultRetryCount is the default number of retries.
const DefaultRetryMaxWaitTime = 10 * time.Second
DefaultRetryMaxWaitTime is the upper bound for the exponential backoff.
const DefaultRetryWaitTime = 500 * time.Millisecond
DefaultRetryWaitTime is the initial wait between retries.
const DefaultTimeout = 30 * time.Second
DefaultTimeout is the default per-request timeout.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a reusable HTTP client backed by resty v3.
Zero value is not usable — use New() to construct.
func New ¶
New builds a Client with sane defaults, then applies the given options.
Defaults:
- RetryCount: 3
- RetryWaitTime: 500ms (grows exponentially with jitter)
- RetryMaxWaitTime: 10s
- Timeout: 30s
- Retry conditions: status 429, 5xx, and 0 (network errors)
- OpenTelemetry: enabled (via otelhttp transport)
Callers MUST call Close() when the client is no longer needed to release internal resources.
func (*Client) Close ¶
func (c *Client) Close()
Close releases internal resources held by the resty client.
type Option ¶
type Option func(*Client)
Option is a functional option that configures a Client.
func WithAuthToken ¶
WithAuthToken sets the default Authorization Bearer token.
func WithBaseURL ¶
WithBaseURL sets a base URL that is prepended to every request path.
client := httpclient.New(httpclient.WithBaseURL("https://api.dev"))
resp, err := client.R(ctx).Get("/v1/users") // → GET https://api.dev/v1/users
func WithBasicAuth ¶
WithBasicAuth sets the default HTTP Basic Authentication credentials.
func WithCookies ¶
WithCookies sets default cookies sent on every request.
func WithHeader ¶
WithHeader is a convenience option that sets a single default header.
func WithHeaders ¶
WithHeaders sets default headers that are sent on every request. Existing per-request headers take precedence.
func WithLogger ¶
WithLogger sets the resty client's logger to the given *slog.Logger. Resty will use it for debug, warning, and error messages during request execution, retries, and middleware processing.
func WithMethodDeleteAllowPayload ¶
WithMethodDeleteAllowPayload configures whether DELETE requests are allowed to carry a payload.
func WithMethodGetAllowPayload ¶
WithMethodGetAllowPayload configures whether GET requests are allowed to carry a body (non-standard but required by some APIs).
func WithOpenTelemetry ¶
func WithOpenTelemetry() Option
WithOpenTelemetry wraps the client's http.RoundTripper with otelhttp.NewTransport, adding distributed tracing, metrics, and context propagation to every outgoing request made through this client.
The tracer and meter providers are obtained from the global OTel SDK (otel.GetTracerProvider / otel.GetMeterProvider). Callers that need custom providers should use WithTransport instead with an otelhttp Transport configured manually.
func WithPathParam ¶
WithPathParam sets a default path parameter (replaces {param} in URL paths).
func WithQueryParam ¶
WithQueryParam sets a default query parameter sent on every request.
func WithRequestMiddleware ¶
func WithRequestMiddleware(m resty.RequestMiddleware) Option
WithRequestMiddleware appends a request middleware that is invoked before every HTTP call during request preparation.
func WithResponseMiddleware ¶
func WithResponseMiddleware(m resty.ResponseMiddleware) Option
WithResponseMiddleware appends a response middleware that is invoked after every HTTP call (including failed retries).
func WithResponseSaveDirectory ¶
WithResponseSaveDirectory sets the directory where response bodies are saved when the request has a SetOutputFileName or when SetResponseSaveToFile(true) is enabled globally.
func WithResponseSaveToFile ¶
WithResponseSaveToFile enables or disables automatic saving of response bodies to files in the configured save directory.
func WithRetryCondition ¶
func WithRetryCondition(condition resty.RetryConditionFunc) Option
WithRetryCondition adds a custom retry condition to the built-in defaults. The condition is evaluated after the default conditions — retries happen when ANY condition returns true.
func WithRetryCount ¶
WithRetryCount overrides the maximum number of retry attempts.
A value of 0 disables retries entirely.
func WithRetryHook ¶
func WithRetryHook(hook resty.RetryHookFunc) Option
WithRetryHook registers a callback that is invoked after each failed attempt.
func WithRetryWaitTime ¶
WithRetryWaitTime sets the initial (min) and maximum delay between retries. The actual wait grows exponentially with jitter between these bounds.
func WithScheme ¶
WithScheme sets the URL scheme (e.g. "http", "https").
func WithTimeout ¶
WithTimeout sets the per-request timeout (dial, TLS handshake, request, response body).
func WithTransport ¶
func WithTransport(transport http.RoundTripper) Option
WithTransport replaces the underlying http.RoundTripper (useful for testing with httptest or injecting custom TLS config).