Documentation
¶
Overview ¶
Package httpx provides a high-level HTTP client with composable middleware for retry, circuit breaking, load balancing, structured logging, and more.
The client is configured via functional options and assembled as a middleware chain around a standard http.RoundTripper:
Logging → User Middlewares → Retry → Circuit Breaker → Balancer → Transport
Quick start ¶
client := httpx.New(
httpx.WithBaseURL("https://api.example.com"),
httpx.WithTimeout(10 * time.Second),
httpx.WithRetry(),
httpx.WithCircuitBreaker(),
)
defer client.Close()
resp, err := client.Get(ctx, "/users/1")
Request builders ¶
NewJSONRequest and NewFormRequest create requests with appropriate Content-Type headers and GetBody set for retry compatibility.
Error handling ¶
Failed requests return *httpx.Error with structured fields (Op, URL, StatusCode). Sentinel errors ErrRetryExhausted, ErrCircuitOpen, and ErrNoHealthy can be checked with errors.Is.
Sub-packages ¶
- middleware — client-side middleware (logging, auth, headers, recovery, request ID)
- retry — configurable retry with backoff and Retry-After support
- circuitbreaker — per-host circuit breaker (closed → open → half-open)
- balancer — client-side load balancing with health checking
- server — production HTTP server with router, middleware, and graceful shutdown
Index ¶
- Variables
- func NewFormRequest(ctx context.Context, method, rawURL string, values url.Values) (*http.Request, error)
- func NewJSONRequest(ctx context.Context, method, url string, body any) (*http.Request, error)
- func NewRequest(ctx context.Context, method, url string, body io.Reader) (*http.Request, error)
- type Client
- func (c *Client) Close()
- func (c *Client) Delete(ctx context.Context, url string) (*Response, error)
- func (c *Client) Do(ctx context.Context, req *http.Request) (*Response, error)
- func (c *Client) Get(ctx context.Context, url string) (*Response, error)
- func (c *Client) HTTPClient() *http.Client
- func (c *Client) Patch(ctx context.Context, url string, body io.Reader) (*Response, error)
- func (c *Client) Post(ctx context.Context, url string, body io.Reader) (*Response, error)
- func (c *Client) Put(ctx context.Context, url string, body io.Reader) (*Response, error)
- type Error
- type ErrorMapper
- type Option
- func WithBalancer(opts ...balancer.Option) Option
- func WithBaseURL(url string) Option
- func WithCircuitBreaker(opts ...circuitbreaker.Option) Option
- func WithEndpoints(eps ...balancer.Endpoint) Option
- func WithErrorMapper(m ErrorMapper) Option
- func WithLogger(l *slog.Logger) Option
- func WithMaxResponseBody(n int64) Option
- func WithMiddleware(mws ...middleware.Middleware) Option
- func WithRetry(opts ...retry.Option) Option
- func WithTimeout(d time.Duration) Option
- func WithTransport(rt http.RoundTripper) Option
- type Response
- func (r *Response) BodyReader() io.Reader
- func (r *Response) Bytes() ([]byte, error)
- func (r *Response) Close() error
- func (r *Response) IsError() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) JSON(v any) error
- func (r *Response) String() (string, error)
- func (r *Response) XML(v any) error
Constants ¶
This section is empty.
Variables ¶
var ( ErrRetryExhausted = retry.ErrRetryExhausted ErrCircuitOpen = circuitbreaker.ErrCircuitOpen ErrNoHealthy = balancer.ErrNoHealthy )
Sentinel errors returned by httpx components. These are aliases for the canonical errors defined in sub-packages, so that errors.Is works regardless of which import the caller uses.
Functions ¶
func NewFormRequest ¶
func NewFormRequest(ctx context.Context, method, rawURL string, values url.Values) (*http.Request, error)
NewFormRequest creates an http.Request with a form-encoded body and sets Content-Type to application/x-www-form-urlencoded. The GetBody function is set so that the request can be retried.
func NewJSONRequest ¶
NewJSONRequest creates an http.Request with a JSON-encoded body and sets Content-Type to application/json.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a high-level HTTP client that composes middleware for retry, circuit breaking, load balancing, logging, and more.
func New ¶
New creates a new Client with the given options.
The middleware chain is assembled as (outermost → innermost):
Logging → User Middlewares → Retry → Circuit Breaker → Balancer → Base Transport
func (*Client) Close ¶
func (c *Client) Close()
Close releases resources associated with the Client, such as background health checker goroutines. It is safe to call multiple times.
func (*Client) HTTPClient ¶
HTTPClient returns the underlying *http.Client for advanced use cases. Mutating the returned client may bypass the configured middleware chain.
type Error ¶
type Error struct {
// Op is the operation that failed (e.g. "Get", "Do").
Op string
// URL is the originally-requested URL.
URL string
// Endpoint is the resolved endpoint URL (after balancing).
Endpoint string
// StatusCode is the HTTP status code, if a response was received.
StatusCode int
// Retries is the number of retry attempts made.
Retries int
// Err is the underlying error.
Err error
}
Error provides structured error information for failed HTTP operations.
type ErrorMapper ¶
ErrorMapper maps an HTTP response to an error. If the response is acceptable, the mapper should return nil. Used by Client to convert non-successful HTTP responses into Go errors.
type Option ¶
type Option func(*clientOptions)
Option configures a Client.
func WithBalancer ¶
WithBalancer configures the load balancer strategy and options.
func WithBaseURL ¶
WithBaseURL sets the base URL prepended to all relative request paths.
func WithCircuitBreaker ¶
func WithCircuitBreaker(opts ...circuitbreaker.Option) Option
WithCircuitBreaker enables per-host circuit breaking.
func WithEndpoints ¶
WithEndpoints sets the endpoints for load balancing.
func WithErrorMapper ¶
func WithErrorMapper(m ErrorMapper) Option
WithErrorMapper sets a function that maps HTTP responses to errors.
func WithLogger ¶
WithLogger enables structured logging of requests and responses.
func WithMaxResponseBody ¶
WithMaxResponseBody limits the number of bytes read from response bodies by Response.Bytes (and by extension String, JSON, XML). If the response body exceeds n bytes, reading stops and returns an error. A value of 0 means no limit (the default).
func WithMiddleware ¶
func WithMiddleware(mws ...middleware.Middleware) Option
WithMiddleware appends user middlewares to the chain. These run between logging and retry in the middleware stack.
func WithTimeout ¶
WithTimeout sets the overall request timeout.
func WithTransport ¶
func WithTransport(rt http.RoundTripper) Option
WithTransport sets the base http.RoundTripper. Defaults to http.DefaultTransport.
type Response ¶
Response wraps http.Response with convenience methods.
func (*Response) BodyReader ¶
BodyReader returns a reader for the response body. If the body has already been read via Bytes/String/JSON/XML, returns a reader over the cached bytes.
func (*Response) Bytes ¶
Bytes reads and returns the entire response body. The body is cached so subsequent calls return the same data.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package balancer provides client-side load balancing as HTTP middleware.
|
Package balancer provides client-side load balancing as HTTP middleware. |
|
Package circuitbreaker provides a per-host circuit breaker as HTTP middleware.
|
Package circuitbreaker provides a per-host circuit breaker as HTTP middleware. |
|
examples
|
|
|
basic-client
command
Basic HTTP client with retry, timeout, and structured logging.
|
Basic HTTP client with retry, timeout, and structured logging. |
|
form-request
command
Demonstrates form-encoded requests for OAuth token endpoints and similar APIs.
|
Demonstrates form-encoded requests for OAuth token endpoints and similar APIs. |
|
load-balancing
command
Demonstrates load balancing across multiple backend endpoints with circuit breaking and health-checked failover.
|
Demonstrates load balancing across multiple backend endpoints with circuit breaking and health-checked failover. |
|
request-id-propagation
command
Demonstrates request ID propagation between server and client.
|
Demonstrates request ID propagation between server and client. |
|
server-basic
command
Basic HTTP server with routing, middleware, health checks, and graceful shutdown.
|
Basic HTTP server with routing, middleware, health checks, and graceful shutdown. |
|
server-protected
command
Production server with CORS, rate limiting, body size limits, and timeouts.
|
Production server with CORS, rate limiting, body size limits, and timeouts. |
|
internal
|
|
|
requestid
Package requestid provides a shared context key for request IDs, allowing both client and server packages to access request IDs without circular imports.
|
Package requestid provides a shared context key for request IDs, allowing both client and server packages to access request IDs without circular imports. |
|
Package middleware provides client-side HTTP middleware for use with httpx.Client or any http.RoundTripper-based transport chain.
|
Package middleware provides client-side HTTP middleware for use with httpx.Client or any http.RoundTripper-based transport chain. |
|
Package retry provides configurable HTTP request retry as client middleware.
|
Package retry provides configurable HTTP request retry as client middleware. |
|
Package server provides a production-ready HTTP server with graceful shutdown, middleware composition, routing, and JSON response helpers.
|
Package server provides a production-ready HTTP server with graceful shutdown, middleware composition, routing, and JSON response helpers. |