httpclient

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 6 Imported by: 0

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

View Source
const DefaultRetryCount = 3

DefaultRetryCount is the default number of retries.

View Source
const DefaultRetryMaxWaitTime = 10 * time.Second

DefaultRetryMaxWaitTime is the upper bound for the exponential backoff.

View Source
const DefaultRetryWaitTime = 500 * time.Millisecond

DefaultRetryWaitTime is the initial wait between retries.

View Source
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

func New(opts ...Option) *Client

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.

func (*Client) R

func (c *Client) R(ctx context.Context) *resty.Request

R returns a fresh resty.Request wired with the supplied context.

The ctx controls cancellation and deadline propagation for HTTP calls made with the returned request.

func (*Client) Resty

func (c *Client) Resty() *resty.Client

Resty exposes the underlying resty client for advanced configuration that is not covered by the Option helpers.

type Option

type Option func(*Client)

Option is a functional option that configures a Client.

func WithAuthToken

func WithAuthToken(token string) Option

WithAuthToken sets the default Authorization Bearer token.

func WithBaseURL

func WithBaseURL(url string) Option

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

func WithBasicAuth(username, password string) Option

WithBasicAuth sets the default HTTP Basic Authentication credentials.

func WithCookies

func WithCookies(cookies ...*http.Cookie) Option

WithCookies sets default cookies sent on every request.

func WithHeader

func WithHeader(key, value string) Option

WithHeader is a convenience option that sets a single default header.

func WithHeaders

func WithHeaders(headers map[string]string) Option

WithHeaders sets default headers that are sent on every request. Existing per-request headers take precedence.

func WithLogger

func WithLogger(logger *slog.Logger) Option

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

func WithMethodDeleteAllowPayload(allow bool) Option

WithMethodDeleteAllowPayload configures whether DELETE requests are allowed to carry a payload.

func WithMethodGetAllowPayload

func WithMethodGetAllowPayload(allow bool) Option

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

func WithPathParam(name, value string) Option

WithPathParam sets a default path parameter (replaces {param} in URL paths).

func WithQueryParam

func WithQueryParam(name, value string) Option

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

func WithResponseSaveDirectory(dir string) Option

WithResponseSaveDirectory sets the directory where response bodies are saved when the request has a SetOutputFileName or when SetResponseSaveToFile(true) is enabled globally.

func WithResponseSaveToFile

func WithResponseSaveToFile(save bool) Option

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

func WithRetryCount(n int) Option

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

func WithRetryWaitTime(waitMin, waitMax time.Duration) Option

WithRetryWaitTime sets the initial (min) and maximum delay between retries. The actual wait grows exponentially with jitter between these bounds.

func WithScheme

func WithScheme(scheme string) Option

WithScheme sets the URL scheme (e.g. "http", "https").

func WithTimeout

func WithTimeout(d time.Duration) Option

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).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL