Documentation
¶
Overview ¶
Package httpx is a thin layer over net/http: a server with production timeouts and graceful shutdown, route groups over ServeMux, middleware chaining, JSON helpers with RFC 9457 errors and domain-error mapping, body binding, and HTML rendering for BFF services.
Handlers stay plain http.HandlerFunc and patterns are ServeMux patterns — anything written for net/http works here unchanged, and anything written for httpx works under bare net/http.
Index ¶
- Constants
- Variables
- func Bind(r *http.Request, v any, opts ...BindOption) error
- func Error(w http.ResponseWriter, status int, detail string)
- func JSON(w http.ResponseWriter, status int, v any)
- func Render(w http.ResponseWriter, r *http.Request, status int, c Renderer) error
- type BindOption
- type Config
- type ErrorMap
- type ErrorWriter
- type Group
- func (g *Group) Delete(pattern string, h http.HandlerFunc)
- func (g *Group) Get(pattern string, h http.HandlerFunc)
- func (g *Group) Group(prefix string, mw ...Middleware) *Group
- func (g *Group) Handle(pattern string, h http.Handler)
- func (g *Group) HandleFunc(pattern string, h http.HandlerFunc)
- func (g *Group) Head(pattern string, h http.HandlerFunc)
- func (g *Group) Options(pattern string, h http.HandlerFunc)
- func (g *Group) Patch(pattern string, h http.HandlerFunc)
- func (g *Group) Post(pattern string, h http.HandlerFunc)
- func (g *Group) Put(pattern string, h http.HandlerFunc)
- func (g *Group) Query(pattern string, h http.HandlerFunc)
- type Middleware
- type Problem
- type Problemer
- type RenderFunc
- type Renderer
- type Server
Constants ¶
const ( DefaultReadHeaderTimeout = 5 * time.Second DefaultReadTimeout = 10 * time.Second DefaultWriteTimeout = 30 * time.Second DefaultIdleTimeout = 120 * time.Second DefaultShutdownGrace = 15 * time.Second DefaultMaxHeaderBytes = 1 << 20 // 1 MiB DefaultMaxBind = int64(1) << 20 // 1 MiB // DefaultMaxBody caps body capture. DefaultMaxBody = 64 << 10 // 64 KiB )
Defaults applied by New and Bind wherever config is zero-valued. Every default exists because Go's own zero (usually "no limit") is the wrong one for production; the numbers live here so they are documented API.
const MethodQuery = "QUERY"
MethodQuery is the HTTP QUERY method (RFC 10008): safe, idempotent queries carried in the request body. Go rc-1.27 added net/http.MethodQuery with the identical value; when this module's floor reaches 1.27, this constant becomes an alias for it — no caller changes either way.
Variables ¶
var ( ErrNotJSON = errors.New("httpx: bind: content type is not JSON") ErrNoContentType = errors.New("httpx: bind: QUERY requires an explicit Content-Type (RFC 10008)") ErrTrailingData = errors.New("httpx: bind: unexpected data after JSON body") )
Bind error sentinels, asserted with errors.Is. Size-limit violations surface as *http.MaxBytesError (use errors.As); an empty body is io.EOF.
Functions ¶
func Bind ¶
func Bind(r *http.Request, v any, opts ...BindOption) error
Bind decodes a JSON request body into v, capped at DefaultMaxBind bytes unless overridden. It reads the body, so it serves POST, PUT, PATCH and QUERY (RFC 10008) identically. A missing Content-Type is assumed JSON — except on QUERY, where RFC 10008 requires servers to fail requests without one (ErrNoContentType). An explicit non-JSON Content-Type is rejected with ErrNotJSON.
Bind holds no ResponseWriter, so exceeding the cap does not mark the connection for closure the way the stdlib's 413 path does; a handler that wants that behavior sets "Connection: close" itself.
func Error ¶
func Error(w http.ResponseWriter, status int, detail string)
Error writes a minimal RFC 9457 response: the status, its canonical title, and the given detail.
func JSON ¶
func JSON(w http.ResponseWriter, status int, v any)
JSON writes v as an application/json response with the given status. If v cannot be marshaled, a 500 Problem is written instead — the encoding failure surfaces before any header goes out, never as a half-written body.
Types ¶
type BindOption ¶
type BindOption func(*bindOptions)
BindOption adjusts a single Bind call.
func MaxBody ¶
func MaxBody(n int64) BindOption
MaxBody overrides the default request-body cap (DefaultMaxBind) for one Bind call.
type Config ¶
type Config struct {
Addr string
ReadHeaderTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
MaxHeaderBytes int
ShutdownGrace time.Duration
}
Config configures New. The zero value of every field is a production default (see the Default constants), not Go's dangerous zero — New(Config{Addr: ":8080"}) is a server with timeouts on.
type ErrorMap ¶
type ErrorMap struct {
// contains filtered or unexported fields
}
ErrorMap translates domain errors into Problem responses: register the service's error taxonomy once at startup, then handlers respond with one line. Build it before serving — it is read-only afterward, so the request path takes no locks.
func NewErrorMap ¶
func NewErrorMap() *ErrorMap
NewErrorMap returns an empty map; unmapped errors respond as a bare 500.
type ErrorWriter ¶
ErrorWriter swaps the RFC 9457 default anywhere httpx itself writes an error on a service's behalf (middleware such as Recover and RateLimit). Nil always means Problem JSON.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group registers routes under a shared prefix and middleware chain. Groups are registration-time sugar: at request time there is only the one underlying ServeMux, so grouping costs nothing per request.
func (*Group) Delete ¶
func (g *Group) Delete(pattern string, h http.HandlerFunc)
Delete registers a DELETE handler for the pattern.
func (*Group) Get ¶
func (g *Group) Get(pattern string, h http.HandlerFunc)
Get registers a GET handler for the pattern.
func (*Group) Group ¶
func (g *Group) Group(prefix string, mw ...Middleware) *Group
Group returns a child group. Its prefix appends to the parent's and its chain extends the parent's; the parent is never mutated. Prefixes are joined verbatim, so pass them without a trailing slash: "/api", "/v1".
func (*Group) Handle ¶
Handle is the escape hatch for anything the typed helpers don't cover. Its signature mirrors ServeMux.Handle exactly: the pattern may carry its own method token, as in g.Handle("PROPFIND /dav/{path...}", h).
func (*Group) HandleFunc ¶
func (g *Group) HandleFunc(pattern string, h http.HandlerFunc)
HandleFunc is Handle for a plain handler func, mirroring ServeMux.
func (*Group) Head ¶
func (g *Group) Head(pattern string, h http.HandlerFunc)
Head registers a HEAD handler for the pattern.
func (*Group) Options ¶
func (g *Group) Options(pattern string, h http.HandlerFunc)
Options registers an OPTIONS handler for the pattern.
func (*Group) Patch ¶
func (g *Group) Patch(pattern string, h http.HandlerFunc)
Patch registers a PATCH handler for the pattern.
func (*Group) Post ¶
func (g *Group) Post(pattern string, h http.HandlerFunc)
Post registers a POST handler for the pattern.
type Middleware ¶
Middleware is the standard chain shape. A type alias on purpose: any func(http.Handler) http.Handler — yours, chi's, the ecosystem's — is assignment-compatible without conversion.
type Problem ¶
type Problem struct {
Type string `json:"type,omitempty"` // URI reference; default "about:blank"
Title string `json:"title,omitempty"` // short, stable per Type; default from status code
Status int `json:"status"` // HTTP status; default 500
Detail string `json:"detail,omitempty"` // occurrence-specific explanation
Instance string `json:"instance,omitempty"` // URI of this occurrence
}
Problem is an RFC 9457 error response (application/problem+json). The helpers fill sensible defaults; fill the struct yourself for a richer error taxonomy — the struct is the API, Error is convenience.
func (Problem) Respond ¶
func (p Problem) Respond(w http.ResponseWriter)
Respond writes the problem with its own status and defaults filled.
type Problemer ¶
type Problemer interface {
Problem() Problem
}
Problemer lets an error type carry its own Problem mapping; ErrorMap checks it before the registry, unwrapping as errors.As does.
type RenderFunc ¶
RenderFunc adapts a plain function to Renderer, the way http.HandlerFunc adapts handlers.
type Renderer ¶
Renderer is anything that can stream itself as HTML. templ components satisfy it natively (identical method); other engines adapt in a few lines — httpx never imports one.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps http.Server and the root route Group — Get, Post, Group and the rest are promoted from the embedded root. Register routes, then call Run.
func New ¶
New returns a Server ready to register routes. Zero-valued config fields get the package defaults.
func (*Server) HTTPServer ¶
HTTPServer exposes the underlying http.Server for needs httpx does not wrap, such as ListenAndServeTLS or connection-state hooks.
func (*Server) Run ¶
Run serves until ctx is canceled, then shuts down gracefully within the configured ShutdownGrace. Signal wiring belongs to the caller:
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() err := srv.Run(ctx)
It returns the shutdown error on a graceful stop (nil when the drain succeeded), or the serve error if the server could not run at all.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP makes Server a plain http.Handler, usable under httptest or mounted inside another server without Run.
func (*Server) Use ¶
func (s *Server) Use(mw ...Middleware)
Use appends middleware wrapped around the entire mux — every route, and unmatched (404) requests too. Must be called before Run or ServeHTTP.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package client is httpx's outbound side: an http.Client wrapper with production transport tuning, a mandatory timeout, a circuit-breaker hook, W3C traceparent propagation from the request context, and opt-in request/response logging that inherits the supplied logger's redaction.
|
Package client is httpx's outbound side: an http.Client wrapper with production transport tuning, a mandatory timeout, a circuit-breaker hook, W3C traceparent propagation from the request context, and opt-in request/response logging that inherits the supplied logger's redaction. |
|
Package middleware is httpx's standard middleware set.
|
Package middleware is httpx's standard middleware set. |