httpx

package
v0.0.0-...-bccdb8e Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package httpx provides explicit HTTP helpers for application services. It is built on the standard net/http package with http.ServeMux as the router. No hidden middleware injection or reflection-based route discovery is used.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Adapt

func Adapt(handler HandlerFunc, encoder ErrorEncoder) http.HandlerFunc

Adapt converts an error-returning HandlerFunc into a standard http.HandlerFunc. If the handler returns an error and an encoder is provided, the encoder writes the response. Otherwise DefaultErrorEncoder is used.

func DecodeJSON

func DecodeJSON(r *http.Request, dst any, maxBytes int64) error

DecodeJSON decodes a JSON request body into dst. Unknown fields are rejected and the body size is limited to maxBytes. Pass maxBytes ≤ 0 to use the default limit of 1 MiB.

For global body size enforcement with proper Connection: close handling, use the MaxBody middleware in the request chain before calling DecodeJSON.

func DefaultErrorEncoder

func DefaultErrorEncoder(w http.ResponseWriter, _ *http.Request, err error)

DefaultErrorEncoder writes a safe default error response. It checks whether the error implements StatusCode() int for status mapping. Internal causes are never forwarded to the client.

func DrainAndClose

func DrainAndClose(r *http.Request)

DrainAndClose fully reads and closes the request body. Call this in handlers that do not consume the body to prevent keep-alive connection issues.

func HealthCheck

func HealthCheck(w http.ResponseWriter, r *http.Request) error

HealthCheck is a simple health probe handler that always returns 200 OK. Mount at /healthz or /health/live.

func NewServer

func NewServer(cfg ServerConfig, handler http.Handler) *http.Server

NewServer creates an http.Server with the provided config and handler. BaseContext is set to context.Background() explicitly.

func PathValue

func PathValue(r *http.Request, name string) string

PathValue extracts a named path parameter from the request using the standard ServeMux wildcard syntax {name}. Equivalent to r.PathValue(name) — provided as documentation anchor.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext retrieves the request ID stored in the context.

func WithRequestID

func WithRequestID(ctx context.Context, id string) context.Context

WithRequestID stores a request ID in the context.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, body any) error

WriteJSON writes a JSON response body with the given status code. The Content-Type header is set to application/json.

func WriteProblem

func WriteProblem(w http.ResponseWriter, status int, body any) error

WriteProblem writes an application/problem+json response (RFC 7807). Use this for error responses at transport boundaries.

Types

type ErrorEncoder

type ErrorEncoder interface {
	EncodeError(http.ResponseWriter, *http.Request, error)
}

ErrorEncoder writes errors to the client.

type HandlerFunc

type HandlerFunc func(http.ResponseWriter, *http.Request) error

HandlerFunc allows handlers to return errors explicitly. This avoids the pattern of writing to the response and silently returning, which makes error handling inconsistent across handlers.

func Chain

func Chain(handler HandlerFunc, middleware ...Middleware) HandlerFunc

Chain applies middleware in declaration order so the first middleware is the outermost wrapper.

Chain(h, A, B, C) → A(B(C(h)))

func ReadinessCheck

func ReadinessCheck(probe func(ctx context.Context) error) HandlerFunc

ReadinessCheck returns a HandlerFunc that calls the provided probe function. If the probe returns an error the endpoint responds with 503. Mount at /readyz or /health/ready.

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Middleware transforms a handler.

func MaxBody

func MaxBody(maxBytes int64) Middleware

MaxBody returns a Middleware that limits the request body to maxBytes. Requests exceeding this limit will be rejected with a 413 response.

func Recovery

func Recovery(onPanic func(recovered any, stack []byte), enc ...ErrorEncoder) Middleware

Recovery returns a Middleware that catches panics and converts them to a 500 application/problem+json response. Stack traces are written via the onPanic callback (usually stderr or a logger sink) and are never forwarded to the client.

The optional enc parameter controls how the 500 is encoded. When enc is nil, DefaultErrorEncoder is used, which always produces application/problem+json. Pass the same ErrorEncoder used by Adapt so that the panic path is encoded identically to any other error (e.g. same Content-Type, same body shape, same request-ID injection).

Usage:

httpx.Chain(handler, httpx.Recovery(logPanic, enc))

func RequireContentType

func RequireContentType(contentType string) Middleware

RequireContentType returns a Middleware that rejects requests whose Content-Type does not match the required value. Methods without a body (GET, HEAD, OPTIONS, DELETE) are skipped. On mismatch, an error is returned so the ErrorEncoder can produce a consistent response format (e.g., application/problem+json).

type Problem

type Problem struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

Problem is the default error response shape used by DefaultErrorEncoder.

type ServerConfig

type ServerConfig struct {
	Addr           string
	ReadTimeout    time.Duration
	WriteTimeout   time.Duration
	IdleTimeout    time.Duration
	MaxHeaderBytes int
}

ServerConfig carries the HTTP server settings. All timeout fields must be set explicitly; zero values are not treated as "unlimited" — the caller must make an intentional choice.

Body size enforcement is handled by the MaxBody middleware, not at the server level, to allow per-route control.

Jump to

Keyboard shortcuts

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