Documentation
¶
Overview ¶
Package httpx provides a fluent HTTP client with retries, request tracing and response helpers.
Index ¶
- Constants
- Variables
- func IsTimeout(err error) bool
- func ToBytes(resp *Response, err error) ([]byte, error)
- func ToJSON[T any](resp *Response, err error) (T, error)
- func ToString(resp *Response, err error) (string, error)
- type APIKeyAuth
- type APIKeyQueryAuth
- type Auth
- type BasicAuth
- type BearerAuth
- type Client
- func (c *Client) Close()
- func (c *Client) DELETE(url string) *RequestBuilder
- func (c *Client) GET(url string) *RequestBuilder
- func (c *Client) HEAD(url string) *RequestBuilder
- func (c *Client) OPTIONS(url string) *RequestBuilder
- func (c *Client) PATCH(url string) *RequestBuilder
- func (c *Client) POST(url string) *RequestBuilder
- func (c *Client) PUT(url string) *RequestBuilder
- func (c *Client) QUERY(url string) *RequestBuilder
- type HTTPError
- type Logger
- type Middleware
- type Option
- func WithAuth(auth Auth) Option
- func WithBaseURL(baseURL string) Option
- func WithCheckRedirect(fn func(req *http.Request, via []*http.Request) error) Option
- func WithClientName(value string) Option
- func WithCookieJar(jar http.CookieJar) Option
- func WithHTTPClient(client *http.Client) Option
- func WithHeader(key, value string) Option
- func WithLogger(logger Logger) Option
- func WithMaxResponseBytes(n int64) Option
- func WithMiddleware(m ...Middleware) Option
- func WithPoolConfig(cfg PoolConfig) Option
- func WithProxy(proxy func(*http.Request) (*url.URL, error)) Option
- func WithQueryParam(key, value string) Option
- func WithRequestHook(h RequestHook) Option
- func WithResponseHook(h ResponseHook) Option
- func WithRetryPolicy(p RetryPolicy) Option
- func WithTLSConfig(cfg *tls.Config) Option
- func WithTimeout(timeout time.Duration) Option
- func WithTracer(tracer Tracer) Option
- func WithTransport(transport http.RoundTripper) Option
- type PoolConfig
- type RequestBuilder
- func (rb *RequestBuilder) Auth(auth Auth) *RequestBuilder
- func (rb *RequestBuilder) Body(body io.Reader) *RequestBuilder
- func (rb *RequestBuilder) Debug() *RequestBuilder
- func (rb *RequestBuilder) Do(ctx context.Context) (*Response, error)
- func (rb *RequestBuilder) Field(key, value string) *RequestBuilder
- func (rb *RequestBuilder) Fields(fields url.Values) *RequestBuilder
- func (rb *RequestBuilder) File(fieldName, filePath string) *RequestBuilder
- func (rb *RequestBuilder) FileReader(fieldName string, r io.Reader, filename string, contentType ...string) *RequestBuilder
- func (rb *RequestBuilder) Form(fields map[string]string) *RequestBuilder
- func (rb *RequestBuilder) FormValues(values url.Values) *RequestBuilder
- func (rb *RequestBuilder) Header(key, value string) *RequestBuilder
- func (rb *RequestBuilder) Headers(headers map[string]string) *RequestBuilder
- func (rb *RequestBuilder) IdempotencyKey(key string) *RequestBuilder
- func (rb *RequestBuilder) JSON(v any) *RequestBuilder
- func (rb *RequestBuilder) PathParam(name, value string) *RequestBuilder
- func (rb *RequestBuilder) QueryParam(key, value string) *RequestBuilder
- func (rb *RequestBuilder) QueryParams(params map[string]string) *RequestBuilder
- func (rb *RequestBuilder) Retryable() *RequestBuilder
- func (rb *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder
- type RequestHook
- type Response
- type ResponseHook
- type RetryPolicy
- type TraceInfo
- type Tracer
Constants ¶
const Version = "v1.0.1"
Variables ¶
var ErrEmptyBody = errors.New("httpx: empty response body")
ErrEmptyBody is returned by ToJSON when a successful response has no body (for example 204).
Functions ¶
func ToBytes ¶
ToBytes reads and closes a successful response body, subject to the max response size.
Types ¶
type APIKeyAuth ¶
APIKeyAuth sends an API key in a request header, for example X-API-Key. Header must be a non-empty header name and Key must be non-empty.
type APIKeyQueryAuth ¶
APIKeyQueryAuth sends an API key as a URL query parameter. Prefer header-based API keys when the server supports them. httpx redacts query strings from its logs, traces and errors, but proxies and servers may still record them.
type Auth ¶
Auth injects authentication into an outgoing request.
func NewAPIKeyAuth ¶
NewAPIKeyAuth creates an API key authentication provider that sends key in header. Example: NewAPIKeyAuth("X-API-Key", "your-api-key").
func NewAPIKeyQueryAuth ¶
NewAPIKeyQueryAuth creates an API key authentication provider that sends key in a query parameter. Example: NewAPIKeyQueryAuth("api_key", "your-api-key").
func NewBasicAuth ¶
NewBasicAuth creates an HTTP Basic authentication provider.
func NewBearerAuth ¶
type BasicAuth ¶
type BasicAuth struct{ Username, Password string }
BasicAuth applies HTTP Basic authentication.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client wraps http.Client and provides defaults and fluent request builders. A Client is safe for concurrent use once constructed.
func (*Client) Close ¶
func (c *Client) Close()
Close releases idle connections held by the client's transport.
func (*Client) DELETE ¶
func (c *Client) DELETE(url string) *RequestBuilder
func (*Client) GET ¶
func (c *Client) GET(url string) *RequestBuilder
Standard HTTP method constructors.
func (*Client) HEAD ¶
func (c *Client) HEAD(url string) *RequestBuilder
func (*Client) OPTIONS ¶
func (c *Client) OPTIONS(url string) *RequestBuilder
func (*Client) PATCH ¶
func (c *Client) PATCH(url string) *RequestBuilder
func (*Client) POST ¶
func (c *Client) POST(url string) *RequestBuilder
func (*Client) PUT ¶
func (c *Client) PUT(url string) *RequestBuilder
func (*Client) QUERY ¶
func (c *Client) QUERY(url string) *RequestBuilder
QUERY initiates a safe, idempotent server-side query. The query definition is typically sent in the request body, which should have an appropriate Content-Type. Servers and intermediaries must support the QUERY method for this to work.
type HTTPError ¶
type HTTPError struct {
Method string
URL string
StatusCode int
Status string
Header http.Header
Body string
}
HTTPError represents a non-2xx HTTP response. Body is a bounded excerpt (about 4 KiB). URL never includes the query string.
type Logger ¶
type Logger interface {
Debug(ctx context.Context, msg string, keysAndValues ...any)
Info(ctx context.Context, msg string, keysAndValues ...any)
Error(ctx context.Context, msg string, keysAndValues ...any)
}
Logger is the optional structured logging interface.
type Middleware ¶
type Middleware func(http.RoundTripper) http.RoundTripper
Middleware wraps a RoundTripper, for example to add OpenTelemetry, metrics or rate limiting. Middlewares run in the order given: the first one is the outermost.
type Option ¶
type Option func(*Client)
Option configures a Client. Options only record intent; the HTTP client is built once at the end of New, so the order of options does not matter.
func WithBaseURL ¶
WithBaseURL sets a base URL prepended to relative request paths. Path segments of the base are preserved: base "https://x.com/v1" and path "/users" give "https://x.com/v1/users".
func WithCheckRedirect ¶
WithCheckRedirect sets the redirect policy. Return http.ErrUseLastResponse to stop following.
func WithClientName ¶
WithClientName sets a Header `X-Client-Name`.
func WithCookieJar ¶
WithCookieJar sets the cookie jar.
func WithHTTPClient ¶
WithHTTPClient uses a copy of a custom *http.Client; the original is never modified. Its Timeout becomes the default request timeout unless WithTimeout is also given.
func WithMaxResponseBytes ¶
WithMaxResponseBytes sets the maximum body size consumed by ToJSON, ToBytes and ToString. Send still exposes a streaming body; callers can stream arbitrarily large responses themselves.
func WithMiddleware ¶
func WithMiddleware(m ...Middleware) Option
WithMiddleware appends RoundTripper middlewares (tracing, metrics, rate limiting, ...).
func WithPoolConfig ¶
func WithPoolConfig(cfg PoolConfig) Option
WithPoolConfig configures connection pooling. Zero values retain the transport defaults. It requires the underlying transport to be an *http.Transport.
func WithQueryParam ¶
WithQueryParam sets a default query parameter.
func WithRequestHook ¶
func WithRequestHook(h RequestHook) Option
func WithResponseHook ¶
func WithResponseHook(h ResponseHook) Option
func WithRetryPolicy ¶
func WithRetryPolicy(p RetryPolicy) Option
WithRetryPolicy configures opt-in retries. Retries are limited to idempotent methods and replayable bodies.
func WithTLSConfig ¶
WithTLSConfig sets the TLS client configuration (custom CAs, client certificates for mTLS, ...). It requires the underlying transport to be an *http.Transport.
func WithTimeout ¶
WithTimeout sets the default timeout for requests. It covers the whole call, including all retry attempts, backoff waits and (until Close) reading the response body. Zero disables the timeout.
func WithTracer ¶
WithTracer sets distributed trace propagation.
func WithTransport ¶
func WithTransport(transport http.RoundTripper) Option
WithTransport sets a custom transport.
type PoolConfig ¶
type PoolConfig struct {
MaxIdleConns int
MaxIdleConnsPerHost int
MaxConnsPerHost int
IdleConnTimeout time.Duration
TLSHandshakeTimeout time.Duration
ResponseHeaderTimeout time.Duration
}
PoolConfig configures the standard HTTP transport connection pool.
type RequestBuilder ¶
type RequestBuilder struct {
// contains filtered or unexported fields
}
RequestBuilder builds an individual HTTP request.
func (*RequestBuilder) Auth ¶
func (rb *RequestBuilder) Auth(auth Auth) *RequestBuilder
Auth overrides client-level authentication for this request.
func (*RequestBuilder) Body ¶
func (rb *RequestBuilder) Body(body io.Reader) *RequestBuilder
Body sets a raw request body. Retries need a replayable body: *bytes.Buffer, *bytes.Reader and *strings.Reader qualify.
func (*RequestBuilder) Debug ¶
func (rb *RequestBuilder) Debug() *RequestBuilder
Debug enables trace output for this request. The report is logged after response headers arrive (or when the request fails), to the logger or to stderr when none is configured.
func (*RequestBuilder) Do ¶ added in v1.0.1
func (rb *RequestBuilder) Do(ctx context.Context) (*Response, error)
Send executes the request and returns the response. The caller must close the response body. The request timeout covers every attempt, and stays active until the body is closed.
func (*RequestBuilder) Field ¶
func (rb *RequestBuilder) Field(key, value string) *RequestBuilder
Field adds a multipart text field.
func (*RequestBuilder) Fields ¶
func (rb *RequestBuilder) Fields(fields url.Values) *RequestBuilder
Fields adds multiple multipart text field values.
func (*RequestBuilder) File ¶
func (rb *RequestBuilder) File(fieldName, filePath string) *RequestBuilder
File attaches a local file as a multipart/form-data upload. It can be called several times, including with the same field name; parts are sent in call order.
func (*RequestBuilder) FileReader ¶
func (rb *RequestBuilder) FileReader(fieldName string, r io.Reader, filename string, contentType ...string) *RequestBuilder
FileReader attaches content from r as a multipart/form-data file part named fieldName, using filename as the uploaded file name. It can be called multiple times and combined with File and Field.
The reader is consumed once, when Send builds the multipart body; the body is buffered in memory so retries can replay it. The caller keeps ownership of r and must close it if it is an io.Closer. Because r is consumed, a builder with FileReader cannot be Sent a second time unless the reader is reset by the caller.
func (*RequestBuilder) Form ¶
func (rb *RequestBuilder) Form(fields map[string]string) *RequestBuilder
Form sets URL-encoded form data with one value per key.
func (*RequestBuilder) FormValues ¶
func (rb *RequestBuilder) FormValues(values url.Values) *RequestBuilder
FormValues sets URL-encoded form data. It supports multiple values for the same key.
func (*RequestBuilder) Header ¶
func (rb *RequestBuilder) Header(key, value string) *RequestBuilder
Header sets a request header.
func (*RequestBuilder) Headers ¶
func (rb *RequestBuilder) Headers(headers map[string]string) *RequestBuilder
Headers sets multiple request headers.
func (*RequestBuilder) IdempotencyKey ¶
func (rb *RequestBuilder) IdempotencyKey(key string) *RequestBuilder
IdempotencyKey sets the Idempotency-Key header and marks the request Retryable, which makes retrying POST and PATCH safe against servers that honor the key.
func (*RequestBuilder) JSON ¶
func (rb *RequestBuilder) JSON(v any) *RequestBuilder
JSON encodes v as JSON. Encoding errors are returned by Send rather than hidden in the body. HTML characters (<, >, &) are not escaped.
func (*RequestBuilder) PathParam ¶
func (rb *RequestBuilder) PathParam(name, value string) *RequestBuilder
PathParam replaces "{name}" in the URL with the escaped value, e.g. "/users/{id}".
func (*RequestBuilder) QueryParam ¶
func (rb *RequestBuilder) QueryParam(key, value string) *RequestBuilder
QueryParam appends a query parameter.
func (*RequestBuilder) QueryParams ¶
func (rb *RequestBuilder) QueryParams(params map[string]string) *RequestBuilder
QueryParams sets query parameters, replacing values for matching keys.
func (*RequestBuilder) Retryable ¶
func (rb *RequestBuilder) Retryable() *RequestBuilder
Retryable explicitly allows this request to be retried when the configured RetryPolicy matches a retryable network error or status code. Use only when repeating the operation is safe, typically with a server-supported idempotency key. Request bodies must be replayable.
func (*RequestBuilder) Timeout ¶
func (rb *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder
Timeout overrides the client-level timeout for this request. It covers all retry attempts.
type RequestHook ¶
RequestHook runs immediately before each network attempt. Hooks must be safe for concurrent calls.
type Response ¶
Response wraps http.Response and exposes trace information and helpers.
func (*Response) Close ¶
Close closes the body. It drains up to 4 KiB to improve keep-alive reuse without allowing an unexpectedly large response to block Close indefinitely.
func (*Response) CopyTo ¶
CopyTo streams the response body to dst without buffering the entire response in memory. It closes the response body when finished.
type ResponseHook ¶
ResponseHook runs after response headers arrive on each attempt. Hooks must be safe for concurrent calls.
type RetryPolicy ¶
type RetryPolicy struct {
MaxAttempts int
InitialBackoff time.Duration
MaxBackoff time.Duration
RetryableStatusCodes []int
RetryNetworkErrors bool
Jitter bool
RespectRetryAfter bool
}
RetryPolicy controls retries. MaxAttempts includes the first attempt. A value below 2 means no retries. Jitter enables full jitter: each backoff is randomized between zero and the exponential backoff cap. When RespectRetryAfter is set and the server asks for a delay longer than MaxBackoff (when positive), the request is not retried and the response is returned to the caller instead of hammering the server too early.
func StandardRetryPolicy ¶
func StandardRetryPolicy() RetryPolicy
StandardRetryPolicy returns a conservative policy for common transient failures. It makes up to three total attempts, retries network errors and HTTP 429/502/503/504, uses capped exponential backoff with full jitter, and honors Retry-After when present.
type TraceInfo ¶
type TraceInfo struct {
Method string
URL string
Path string
StatusCode int
DNSLookup time.Duration
ConnTime time.Duration
TCPConnTime time.Duration
TLSHandshake time.Duration
ServerTime time.Duration
ResponseTime time.Duration
TotalTime time.Duration
IsConnReused bool
IsConnWasIdle bool
ConnIdleTime time.Duration
RequestAttempt int
RemoteAddr string
// contains filtered or unexported fields
}
TraceInfo contains timing and connection information collected with net/http/httptrace. Durations are best-effort and some fields remain zero when a connection is reused, a proxy is involved, or the transport does not emit the corresponding hook. TotalTime measures the time until response headers are available. URL never includes the query string, which may carry secrets.