Documentation
¶
Overview ¶
Package webhttp provides resilient server-side HTTP plumbing for building small services on top of net/http.
It bundles the pieces almost every server ends up hand-rolling:
- request-id injection plus one-line access logging (RequestLogger),
- a status recorder that stays transparent to http.ResponseController and also implements http.Flusher/http.Hijacker/io.ReaderFrom passthroughs, so both ResponseController-based and direct-type-assertion callers (plus the sendfile fast path) keep working (StatusRecorder),
- a composable middleware set: an ordering combinator (Chain), a panic recoverer (Recoverer), baseline response security headers (SecurityHeaders), access logging as middleware (Logging), and a JSON per-route timeout (RouteTimeout), plus a spoof-aware client-IP resolver that reads X-Forwarded-For only from trusted proxy hops (ClientIP),
- JSON response and error helpers (WriteJSON, WriteJSONStatus, Ok, WriteError),
- request-prelude helpers for body limiting, method gating, and JSON decoding (LimitBody, RequireMethod, DecodeBody),
- an HTTP readiness gate for load balancers (Ready, ReadinessHandler),
- a graceful server bootstrap (NewServer, Run).
The middleware share the standard func(http.Handler) http.Handler shape (the Middleware alias) and compose with Chain, whose first-listed entry is the outermost wrapper. A typical stack is Chain(mux, Logging(), Recoverer(), SecurityHeaders()): logging outermost so a recovered panic is logged as its 500 rather than a misleading 200.
webhttp is the inbound-server counterpart to httpx (github.com/cplieger/httpx), which is the outbound-client toolkit: httpx makes resilient requests going OUT, webhttp handles the requests coming IN. The two are complementary and share no code.
The package has zero dependencies beyond the standard library. It ships the mechanism only; each consuming application layers its own route table, error taxonomy, and named helpers on top.
Index ¶
- Constants
- func Chain(h http.Handler, mw ...Middleware) http.Handler
- func ClientIP(r *http.Request, trusted ...*net.IPNet) string
- func DecodeBody(w http.ResponseWriter, r *http.Request, v any, errMsg string) bool
- func DecodeBodyOptional(w http.ResponseWriter, r *http.Request, v any)
- func JSONHeaders(w http.ResponseWriter)
- func LimitBody(w http.ResponseWriter, r *http.Request, maxBytes int64)
- func NewRequestID() string
- func NewServer(handler http.Handler, opts ...ServerOption) *http.Server
- func Ok(w http.ResponseWriter)
- func ReadinessHandler(c ReadinessChecker) http.HandlerFunc
- func RequestIDFromContext(ctx context.Context) string
- func RequestLogger(next http.Handler, opts ...LogOption) http.Handler
- func RequireMethod(w http.ResponseWriter, r *http.Request, method string) bool
- func RouteTimeout(h http.Handler, d time.Duration, msg string) http.Handler
- func Run(ctx context.Context, srv *http.Server, ln net.Listener, ...) error
- func ValidRequestID(s string) bool
- func WithRequestID(ctx context.Context, id string) context.Context
- func WriteError(w http.ResponseWriter, r *http.Request, status int, code, msg string)
- func WriteJSON(w http.ResponseWriter, v any)
- func WriteJSONStatus(w http.ResponseWriter, code int, v any)
- type ErrorResponse
- type LogOption
- type Middleware
- type ReadinessChecker
- type Ready
- type RecoverOption
- type RunOption
- type SecurityOption
- func WithCOOP(v string) SecurityOption
- func WithCSP(policy string) SecurityOption
- func WithFrameOptions(v string) SecurityOption
- func WithHSTS(maxAge time.Duration, includeSubdomains, preload bool) SecurityOption
- func WithPermissionsPolicy(v string) SecurityOption
- func WithReferrerPolicy(v string) SecurityOption
- type ServerOption
- func WithErrorLog(l *log.Logger) ServerOption
- func WithIdleTimeout(d time.Duration) ServerOption
- func WithMaxHeaderBytes(n int) ServerOption
- func WithReadHeaderTimeout(d time.Duration) ServerOption
- func WithReadTimeout(d time.Duration) ServerOption
- func WithWriteTimeout(d time.Duration) ServerOption
- type StatusRecorder
- func (s *StatusRecorder) Flush()
- func (s *StatusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (s *StatusRecorder) ReadFrom(src io.Reader) (int64, error)
- func (s *StatusRecorder) Status() int
- func (s *StatusRecorder) Unwrap() http.ResponseWriter
- func (s *StatusRecorder) Write(b []byte) (int, error)
- func (s *StatusRecorder) WriteHeader(code int)
- func (s *StatusRecorder) Wrote() bool
Examples ¶
Constants ¶
const HeaderRequestID = "X-Request-ID"
HeaderRequestID is the canonical request-id header. RequestLogger reads it from the inbound request and echoes it on the response.
const MaxJSONBody int64 = 1 << 20
MaxJSONBody is the default maximum JSON request-body size (1 MiB) applied by DecodeBody and DecodeBodyOptional.
Variables ¶
This section is empty.
Functions ¶
func Chain ¶
func Chain(h http.Handler, mw ...Middleware) http.Handler
Chain wraps h with the given middlewares and returns the composed handler. The FIRST middleware listed becomes the OUTERMOST wrapper: it is the first to see the request on the way in and the last to touch the response on the way out. The LAST middleware listed sits closest to h.
So Chain(h, A, B, C) is equivalent to A(B(C(h))): a request flows A -> B -> C -> h and the response unwinds h -> C -> B -> A. List middlewares in the order you want them to execute; a typical stack puts logging outermost so it observes the final status, then a panic recoverer, then app concerns:
handler := webhttp.Chain(mux, webhttp.Logging(), // outermost: logs every request webhttp.Recoverer(), // catches panics from everything below it webhttp.SecurityHeaders(), // sets headers before the app runs )
A nil middleware in the list is skipped, so callers can include entries conditionally.
func ClientIP ¶
ClientIP returns the best-effort client IP for r.
The spoofing model is the point of this helper. X-Forwarded-For is set by clients and intermediaries and is trivially forgeable, so it is consulted ONLY when the immediate TCP peer (the host part of r.RemoteAddr) is a proxy you control, i.e. it falls inside one of the caller-supplied trusted ranges:
- With NO trusted ranges, or when the direct peer is not inside one, the forwarded header is ignored entirely and the peer address (which cannot be spoofed at this layer) is returned. This is the safe default: no header a client sends can move the result off the real socket peer.
- When the peer IS a trusted proxy, X-Forwarded-For is walked from the RIGHT. Each entry that is itself a trusted proxy is skipped (those are your own hops, which appended the address they saw); the first untrusted entry from the right is returned as the client. A malformed entry at that boundary stops the walk, and the peer is returned.
The right-to-left, skip-trusted walk is the only correct reading when the proxy APPENDS the peer it observed to X-Forwarded-For (as Caddy and most reverse proxies do): the LEFTMOST entry is then whatever the client SENT and is attacker-controlled, while the rightmost entries are the trustworthy hops. Consequently the trusted set must contain EVERY proxy hop between the client and this server; if a hop is missing from the set the walk stops there and that hop's address is returned as the client.
X-Real-IP is deliberately NOT consulted: it is client-settable and a proxy such as Caddy does not overwrite it, so honoring it would reintroduce a spoof vector. It can return as an explicit opt-in if a proxy that overwrites it is ever adopted.
The caller supplies the trusted CIDRs (typically the reverse proxy's address range); the library hardcodes none. A malformed r.RemoteAddr with no port is used verbatim as the host and, being unparseable, is never trusted.
func DecodeBody ¶
DecodeBody limits the body to MaxJSONBody and decodes exactly one JSON value into v. The decoded value must be the entire body: trailing data or a second JSON value is rejected. On any decode failure it writes a 400 error response (code "bad_request") carrying errMsg and returns false; on success it returns true.
func DecodeBodyOptional ¶
func DecodeBodyOptional(w http.ResponseWriter, r *http.Request, v any)
DecodeBodyOptional limits the body to MaxJSONBody and attempts a JSON decode into v, ignoring any error. Use it when the body is optional and a missing or malformed body should leave v at its zero value rather than fail the request.
func JSONHeaders ¶
func JSONHeaders(w http.ResponseWriter)
JSONHeaders sets the standard JSON response headers: an application/json content type and the X-Content-Type-Options: nosniff guard against MIME sniffing. Call it before WriteHeader.
func LimitBody ¶
func LimitBody(w http.ResponseWriter, r *http.Request, maxBytes int64)
LimitBody caps the request body at maxBytes by replacing r.Body with an http.MaxBytesReader. A read past the limit then fails and the server responds 413 instead of buffering an unbounded payload. Call it before reading the body.
func NewRequestID ¶
func NewRequestID() string
NewRequestID returns a fresh request id: 16 cryptographically random bytes, hex-encoded to 32 characters. If the system random source fails, it falls back to a UTC timestamp in the "20060102T150405" layout, which contains no dot and stays within the ValidRequestID character set.
func NewServer ¶
func NewServer(handler http.Handler, opts ...ServerOption) *http.Server
NewServer builds an *http.Server for handler with streaming-safe defaults: ReadHeaderTimeout 10s (a slowloris guard), IdleTimeout 120s, MaxHeaderBytes 1 MiB, and ReadTimeout/WriteTimeout left unset (0) so SSE, WebSocket, and other long-lived responses work out of the box. Options override the defaults.
Because ReadTimeout and WriteTimeout are unset by default, only header reading is time-bounded (by ReadHeaderTimeout); a slow request BODY is not. A non-streaming handler should add WithReadTimeout to bound slowloris-style slow bodies. A streaming handler, which cannot use a whole-request timeout, should instead apply per-request deadlines via http.ResponseController.SetReadDeadline/SetWriteDeadline. Note that MaxBytesReader (see LimitBody) bounds body SIZE, not the time taken to send it.
func Ok ¶
func Ok(w http.ResponseWriter)
Ok writes a 200 response with the JSON body {"ok":true}. It is the canonical success acknowledgement for an endpoint that has no other payload.
Example ¶
package main
import (
"fmt"
"net/http/httptest"
"github.com/cplieger/webhttp"
)
func main() {
rr := httptest.NewRecorder()
webhttp.Ok(rr)
fmt.Print(rr.Body.String())
}
Output: {"ok":true}
func ReadinessHandler ¶
func ReadinessHandler(c ReadinessChecker) http.HandlerFunc
ReadinessHandler returns a handler that reports serving state as JSON: 200 with {"status":"ok"} when c reports ready, otherwise 503 with {"status":"unready","reason":"starting up or shutting down"}.
This is the HTTP SERVING-STATE gate (note the lowercase "ok"), meant for a load balancer asking "should this instance receive traffic right now?". It is deliberately distinct from the cplieger health library's container file-marker probe, which answers {"status":"OK","timestamp":…} for a Docker HEALTHCHECK asking "is the process alive?". The two are complementary and are not the same endpoint.
func RequestIDFromContext ¶
RequestIDFromContext returns the request id stored in ctx by WithRequestID, or "" if none is present.
func RequestLogger ¶
RequestLogger returns middleware that gives each request a request id, echoes it on the response HeaderRequestID header, threads it through the request context (see RequestIDFromContext), and emits one access-log line at Info after next returns:
logger.Info("http", "method", …, "path", …, "status", …,
"duration_ms", …, "request_id", …)
It records the status via a StatusRecorder that stays transparent to http.ResponseController, so wrapped handlers can still Flush and Hijack. An inbound HeaderRequestID is reused when it satisfies ValidRequestID; otherwise a new id is minted with NewRequestID.
A request matched by WithSkipPaths or WithSkipFunc still gets an id minted, echoed, and threaded, but is served through the raw writer with no recorder, no access-log line, and no metric hook.
The access-log line and metric hook are emitted from a deferred call, so a handler that panics is still logged (the status shows the recorded value) before the panic continues up the stack to net/http.
func RequireMethod ¶
RequireMethod reports whether the request method equals method. On a mismatch it sets the RFC 9110 Allow header to method, writes a 405 error response (code "method_not_allowed"), and returns false, so a handler can guard with:
if !webhttp.RequireMethod(w, r, http.MethodPost) {
return
}
func RouteTimeout ¶
RouteTimeout wraps h with http.TimeoutHandler so a handler that runs longer than d is cut off with a 503, but replaces net/http's plain-text/HTML timeout body with a JSON ErrorResponse ({"error":msg,"code":"timeout"}) served as application/json. An empty msg defaults to "request timed out".
A non-positive d disables the timeout: h is returned unwrapped, so its response passes through untouched with no 503 relabeling. (http.TimeoutHandler with a zero or negative duration would otherwise fire the timeout immediately.)
The JSON relabeling keys on status alone: any 503 that reaches the client WITHOUT a Content-Type already set is served as application/json, because the wrapper cannot tell http.TimeoutHandler's own timeout envelope apart from a downstream handler's intentional 503. A handler that emits its own 503 must therefore set an explicit Content-Type, or it will be relabeled application/json (its body bytes are left unchanged; only the headers are added).
It CANNOT wrap streaming or hijacking handlers: http.TimeoutHandler buffers the entire response in memory to be able to discard it on timeout, so SSE, WebSocket upgrades, and other long-lived or flushing responses do not work through it. Apply RouteTimeout only to bounded request/response handlers, and use per-request deadlines (http.ResponseController.SetWriteDeadline) for streaming routes instead.
Because the timeout body is produced inside http.TimeoutHandler, outside request scope, it carries no request_id (unlike WriteError). The 503 envelope is otherwise identical to the package's other JSON errors.
func Run ¶
func Run(ctx context.Context, srv *http.Server, ln net.Listener, onShutdown func(ctx context.Context), opts ...RunOption) error
Run serves srv on ln until ctx is cancelled, then shuts down gracefully.
It starts srv.Serve(ln) in a goroutine (treating http.ErrServerClosed as a clean stop) and blocks until either ctx is cancelled or Serve returns on its own. On cancellation it calls srv.Shutdown with a fresh context bounded by the shutdown grace period, then, if onShutdown is non-nil, calls it with another grace-bounded context for application teardown. Run returns the first non-ErrServerClosed error it observes (a serve error, else a shutdown error), or nil on a clean graceful stop.
The caller binds ln up front (for example with net.ListenConfig.Listen) so a port-in-use error surfaces synchronously before Run is called, and passes application teardown as onShutdown.
func ValidRequestID ¶
ValidRequestID reports whether s is a well-formed request id: between 1 and 64 characters, each an ASCII letter, digit, underscore, or hyphen. Anything else (empty, too long, or containing another byte) is rejected, so a client cannot smuggle log-forging newlines or header-splitting content through the echoed id.
Example ¶
package main
import (
"fmt"
"github.com/cplieger/webhttp"
)
func main() {
fmt.Println(webhttp.ValidRequestID("abc-123_XYZ"))
fmt.Println(webhttp.ValidRequestID("bad id"))
}
Output: true false
func WithRequestID ¶
WithRequestID returns a copy of ctx carrying the request id.
func WriteError ¶
WriteError writes an ErrorResponse with the given HTTP status: msg becomes Error, code becomes Code, and the request id is pulled from the request context (via RequestIDFromContext) so a client can correlate the failure with the access log. It is nil-safe: when r is nil the RequestID field stays empty.
WriteError ships the MECHANISM only. Each consuming application keeps its own named-helper and error-code taxonomy on top of it.
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/cplieger/webhttp"
)
func main() {
rr := httptest.NewRecorder()
// r may be nil; the request_id field is then omitted.
webhttp.WriteError(rr, nil, http.StatusBadRequest, "bad_request", "invalid payload")
fmt.Print(rr.Body.String())
}
Output: {"error":"invalid payload","code":"bad_request"}
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, v any)
WriteJSON writes v as a JSON body with a 200 status.
func WriteJSONStatus ¶
func WriteJSONStatus(w http.ResponseWriter, code int, v any)
WriteJSONStatus sets the JSON headers, writes the status code, and encodes v as the response body. The status is committed before encoding begins, so an encode failure cannot change it; such a failure is logged at Warn rather than returned, because the response line is already on the wire.
Types ¶
type ErrorResponse ¶
type ErrorResponse struct {
// Error is the human-readable error message.
Error string `json:"error"`
// Code is an optional machine-readable error code.
Code string `json:"code,omitempty"`
// RequestID is the request id for log correlation, when available.
RequestID string `json:"request_id,omitempty"`
}
ErrorResponse is the JSON error envelope written by WriteError. Code and RequestID are omitted from the output when empty.
type LogOption ¶
type LogOption func(*logConfig)
LogOption configures RequestLogger.
func WithLogger ¶
WithLogger sets the slog.Logger used for access-log lines. Defaults to slog.Default().
func WithRecordMetric ¶
WithRecordMetric registers a hook invoked once per logged request with the final method, path, status, and latency. It fires from a deferred call, so a panicking handler is still recorded. Requests skipped via WithSkipPaths or WithSkipFunc are excluded from the hook as well as from access logging: a stream's open-to-close duration paired with a synthetic status is misleading, which is the whole reason the path is skipped.
func WithSkipFunc ¶
WithSkipFunc registers a predicate; when it returns true for a request, that request is passed through WITHOUT an access-log line or metric (like a WithSkipPaths match), while the request id is still minted, echoed, and threaded. Use it for streaming routes with path parameters (e.g. "/ws/{id}") that an exact WithSkipPaths match cannot cover.
func WithSkipPaths ¶
WithSkipPaths marks exact request paths (compared against r.URL.Path) that should pass through WITHOUT an access-log line AND without a metric hook. Use it for long-lived streams (SSE, WebSocket) whose single open-forever request would otherwise emit one misleading high-latency line and a synthetic status at close. The request id is still minted, echoed, and threaded into the context for skipped paths. Because the match is exact, streaming routes with path parameters (e.g. "/ws/{id}") need WithSkipFunc instead.
type Middleware ¶
Middleware is the standard net/http decorator shape: it wraps an http.Handler and returns a new one. It is a type alias, so any plain func(http.Handler) http.Handler value is a Middleware without conversion.
func Logging ¶
func Logging(opts ...LogOption) Middleware
Logging returns a Chain-composable Middleware wrapping RequestLogger with the given options. It is exactly RequestLogger in middleware form; use RequestLogger directly when you are not composing with Chain. See RequestLogger for the request-id and access-log behavior and the available LogOption values.
func Recoverer ¶
func Recoverer(opts ...RecoverOption) Middleware
Recoverer returns middleware that recovers a panic from a downstream handler, logs it at Error with the stack and the request id (via RequestIDFromContext), fires any WithPanicHook callback, and writes a 500 JSON error via WriteError(w, r, 500, "internal_error", "internal server error"). Without it, a handler panic unwinds to net/http, which closes the connection abruptly with no response body.
The http.ErrAbortHandler sentinel is deliberately NOT recovered: per the net/http contract it is re-panicked so the server aborts the response the way the handler intended (it is not logged and fires no hook).
Placement relative to Logging matters. Put Recoverer INSIDE RequestLogger, i.e. Logging outermost, as in Chain(mux, Logging(), Recoverer()): the recovered request then records a 500 before RequestLogger's deferred access line runs, so the request logs as 500. If Recoverer sits OUTSIDE the logger, RequestLogger's deferred line runs during the panic unwind and records the StatusRecorder's default 200, a misleading access line even though the client still receives the 500.
The 500 is best-effort and never double-writes: if the handler already committed the response (wrote headers or body) before panicking, the status is on the wire and cannot be changed, so Recoverer skips the body entirely (it still logs the panic and fires the hook) rather than corrupting the partial response or mislabeling its status under an outer Logging. To detect commitment it observes the response through a StatusRecorder, reusing an existing one (such as RequestLogger's) when present.
func SecurityHeaders ¶
func SecurityHeaders(opts ...SecurityOption) Middleware
SecurityHeaders returns middleware that sets a baseline of response security headers before calling the next handler. Set by default are X-Content-Type-Options: nosniff, X-Frame-Options: DENY, and Referrer-Policy: strict-origin-when-cross-origin. The X-Frame-Options and Referrer-Policy defaults are configurable (override with a value, or omit with an empty string); nosniff is set by default with no option to change it here. Content-Security-Policy, Permissions-Policy, Cross-Origin-Opener-Policy, and Strict-Transport-Security are off unless their options are supplied.
All of these are set BEFORE next runs, so none is immutable: the middleware establishes the baseline but does not lock it. A handler that needs a different value for a specific response can still override (or delete) any of them, nosniff included, on the response header.
type ReadinessChecker ¶
type ReadinessChecker interface {
// Ready reports whether the service should receive traffic right now.
Ready() bool
}
ReadinessChecker is the readiness view ReadinessHandler needs. *Ready satisfies it; a service with a composite readiness model can supply its own implementation.
type Ready ¶
type Ready struct {
// contains filtered or unexported fields
}
Ready is a concurrency-safe readiness flag. Its zero value reports not ready, so a service starts unready until it calls Set(true) once initialization completes, and can flip back to unready during shutdown.
type RecoverOption ¶
type RecoverOption func(*recoverConfig)
RecoverOption configures Recoverer.
func WithPanicHook ¶
func WithPanicHook(fn func(v any, stack []byte)) RecoverOption
WithPanicHook registers a callback invoked with the recovered value and the captured stack when a panic is caught. Use it to increment a metric or notify an error tracker. It runs after the panic is logged and before the 500 response is written; a nil hook is ignored.
func WithRecoverLogger ¶
func WithRecoverLogger(l *slog.Logger) RecoverOption
WithRecoverLogger sets the slog.Logger used to report a recovered panic. Defaults to slog.Default().
type RunOption ¶
type RunOption func(*runConfig)
RunOption configures Run.
func WithShutdownGrace ¶
WithShutdownGrace sets how long Run allows for graceful shutdown: the window for in-flight requests to finish and for the onShutdown teardown to run. Defaults to 5s.
type SecurityOption ¶
type SecurityOption func(*securityConfig)
SecurityOption configures SecurityHeaders.
func WithCOOP ¶
func WithCOOP(v string) SecurityOption
WithCOOP sets the Cross-Origin-Opener-Policy header (e.g. "same-origin"). Unset by default.
func WithCSP ¶
func WithCSP(policy string) SecurityOption
WithCSP sets the Content-Security-Policy header. The library never builds a policy for you: a CSP is application-specific (it must match the app's script and style sources, nonces, or hashes), so pass the exact policy string the app needs. Unset by default.
func WithFrameOptions ¶
func WithFrameOptions(v string) SecurityOption
WithFrameOptions overrides the X-Frame-Options header (default "DENY"). Pass an empty string to omit the header, for example when a Content-Security-Policy frame-ancestors directive supersedes it.
func WithHSTS ¶
func WithHSTS(maxAge time.Duration, includeSubdomains, preload bool) SecurityOption
WithHSTS enables the Strict-Transport-Security header with the given max-age and the includeSubDomains and preload directives. HSTS is OFF by default: enable it only for a service reached exclusively over HTTPS, because a browser that sees the header will refuse plain-HTTP and untrusted-certificate connections to the host for the whole max-age window. A negative max-age is clamped to zero (which instructs browsers to forget the policy).
func WithPermissionsPolicy ¶
func WithPermissionsPolicy(v string) SecurityOption
WithPermissionsPolicy sets the Permissions-Policy header (browser feature gating, e.g. "geolocation=(), camera=()"). Unset by default.
func WithReferrerPolicy ¶
func WithReferrerPolicy(v string) SecurityOption
WithReferrerPolicy overrides the Referrer-Policy header (default "strict-origin-when-cross-origin"). Pass an empty string to omit it.
type ServerOption ¶
ServerOption configures the *http.Server built by NewServer.
func WithErrorLog ¶
func WithErrorLog(l *log.Logger) ServerOption
WithErrorLog sets http.Server.ErrorLog so connection-level errors go to the caller's logger instead of the standard logger. Wire it to slog with slog.NewLogLogger(handler, slog.LevelError).
func WithIdleTimeout ¶
func WithIdleTimeout(d time.Duration) ServerOption
WithIdleTimeout sets http.Server.IdleTimeout, the keep-alive idle deadline.
func WithMaxHeaderBytes ¶
func WithMaxHeaderBytes(n int) ServerOption
WithMaxHeaderBytes sets http.Server.MaxHeaderBytes.
func WithReadHeaderTimeout ¶
func WithReadHeaderTimeout(d time.Duration) ServerOption
WithReadHeaderTimeout sets http.Server.ReadHeaderTimeout, the slowloris guard bounding how long a client may take to send request headers.
func WithReadTimeout ¶
func WithReadTimeout(d time.Duration) ServerOption
WithReadTimeout sets http.Server.ReadTimeout, the deadline for reading the entire request. Leave it unset for streaming request bodies.
func WithWriteTimeout ¶
func WithWriteTimeout(d time.Duration) ServerOption
WithWriteTimeout sets http.Server.WriteTimeout, the deadline for writing the entire response. It is unset by default: streaming apps (SSE, WebSocket, long responses) MUST omit it, because it would cut off an in-progress stream.
type StatusRecorder ¶
type StatusRecorder struct {
http.ResponseWriter
// contains filtered or unexported fields
}
StatusRecorder wraps an http.ResponseWriter to capture the response status code. Middleware that needs to observe the final status (access logging, metrics) wraps the writer in a StatusRecorder.
It stays transparent to streaming in two complementary ways. The Unwrap method lets http.NewResponseController walk to the underlying writer, so ResponseController-based callers reach its Flusher, Hijacker, and deadline setters. It also implements http.Flusher, http.Hijacker, and io.ReaderFrom directly, so a handler or library that type-asserts those interfaces on the writer (as gorilla/websocket does with w.(http.Hijacker)) still works, and io.Copy/http.ServeContent keep the zero-copy sendfile fast path. Each passthrough returns the underlying writer's own result, so, for example, Hijack reports http.ErrNotSupported on an HTTP/2 stream.
func NewStatusRecorder ¶
func NewStatusRecorder(w http.ResponseWriter) *StatusRecorder
NewStatusRecorder wraps w. The recorded status defaults to http.StatusOK (200) and stays there until WriteHeader or the first Write records a status.
func (*StatusRecorder) Flush ¶
func (s *StatusRecorder) Flush()
Flush forwards to the underlying writer via http.ResponseController (which walks the Unwrap chain), so a handler that type-asserts http.Flusher directly still streams through the recorder. A no-op if the underlying writer cannot flush.
func (*StatusRecorder) Hijack ¶
func (s *StatusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack forwards to the underlying writer via http.ResponseController for libraries that hijack the connection through a direct http.Hijacker assertion. Returns an error (e.g. http.ErrNotSupported) when the underlying writer, such as an HTTP/2 stream, cannot be hijacked.
func (*StatusRecorder) ReadFrom ¶
func (s *StatusRecorder) ReadFrom(src io.Reader) (int64, error)
ReadFrom preserves the zero-copy (sendfile) fast path for io.Copy and http.ServeContent when the underlying writer implements io.ReaderFrom. Writing the body implies a 200 status when WriteHeader was not called.
func (*StatusRecorder) Status ¶
func (s *StatusRecorder) Status() int
Status returns the recorded status code, or http.StatusOK if none was set.
func (*StatusRecorder) Unwrap ¶
func (s *StatusRecorder) Unwrap() http.ResponseWriter
Unwrap returns the wrapped http.ResponseWriter. http.NewResponseController walks Unwrap to reach a Flusher, Hijacker, or other optional interface implemented by the underlying writer, so streaming still works through the recorder.
func (*StatusRecorder) Write ¶
func (s *StatusRecorder) Write(b []byte) (int, error)
Write records an implicit 200 status on the first write when WriteHeader was not called (mirroring net/http), then forwards to the wrapped writer.
func (*StatusRecorder) WriteHeader ¶
func (s *StatusRecorder) WriteHeader(code int)
WriteHeader records the first explicit status code and forwards every call to the wrapped writer. Only the first code is recorded, matching net/http's first-code-wins semantics; a later call still forwards (so net/http logs its standard "superfluous WriteHeader" warning) but does not change Status.
func (*StatusRecorder) Wrote ¶
func (s *StatusRecorder) Wrote() bool
Wrote reports whether the response has been committed, i.e. WriteHeader or the first Write (or ReadFrom) has run. Middleware such as Recoverer consults it to avoid writing a second status and body onto a response a handler has already started, which would corrupt the body and mislabel the status.