Documentation
¶
Overview ¶
Package httpstats provides a backend-agnostic observability interface for net/http clients and servers, following the same decoupled design philosophy as gRPC-Go's stats.Handler.
Reference implementations for OpenTelemetry and Prometheus live in the docs/ directory. Copy them into your project to use as a starting point — they are not importable library packages.
Quick Start — Server ¶
Implement the Handler interface for your telemetry backend, or copy a reference implementation from the docs/ directory:
wrapped := httpstats.ServerHandler(myMux, httpstats.WithServerHandler(myHandler))
http.ListenAndServe(":8080", wrapped)
Quick Start — Client ¶
ct := httpstats.NewClientTransport(httpstats.WithClientHandler(myHandler))
client := &http.Client{Transport: ct}
resp, _ := client.Get("https://api.example.com")
Combining Backends ¶
Use MultiHandler to run OTEL (tracing) and Prometheus (metrics) side by side:
composed := httpstats.MultiHandler{otelHandler, promHandler}
wrapped := httpstats.ServerHandler(myMux, httpstats.WithServerHandler(composed))
Mid-Flight Telemetry Enrichment ¶
Downstream handlers can attach labels discovered at runtime (tenant ID, user role) via the Tags container injected into every request context:
func myHandler(w http.ResponseWriter, r *http.Request) {
if tags := httpstats.FromContext(r.Context()); tags != nil {
tags.Set("tenant_id", extractTenant(r))
}
}
Event Lifecycle ¶
Server-side event order:
TagRequest → Begin → InHeader → InData* → OutHeader → OutData* → End
Client-side event order:
TagRequest → Begin → OutHeader → OutData* → InHeader → InData* → End
Connection events (TagConn → HandleConn) fire independently and may overlap with request events.
InData / OutData Asymmetry ¶
Unlike gRPC where payload flows are symmetric, HTTP is asymmetric. The meaning of InData and OutData depends on the Client field:
Server: InData = request body read, OutData = response body written Client: OutData = request body written, InData = response body read
Always check the Client field before interpreting payload direction.
Full-Duplex Concurrency ¶
In HTTP/2 and HTTP/3, the request body can be read concurrently with the response body being written — on different goroutines:
- HandleRequest may be called concurrently for InData/OutData events.
- All byte counters in Handler implementations MUST use sync/atomic.
Client Connection Tracing ¶
The ClientTransport hooks httptrace to emit connection-level timing data. When a new connection is dialed (pool miss), ConnBegin carries:
DNSDuration — time spent resolving the hostname TCPDuration — time spent on the TCP handshake TLSDuration — time spent on the TLS handshake
All durations are zero on reused connections (pool hit). InHeader.TTFB captures the round-trip time from the last request byte to the first response byte — server queuing plus network transit.
Context Immutability ¶
context.Context is immutable — TagRequest can inject state, but downstream handlers cannot push new labels back. Use the Tags container (FromContext / Set) for any label discovered after TagRequest returns.
Naming Strategy ¶
DefaultOperationName uses http.Request.Pattern (Go 1.22+) when available, producing names like "GET /users/{id}". If neither OperationName nor Pattern is set, it falls back to "HTTP {method}". Use WithServerNameFunc or WithClientNameFunc to override with a custom naming scheme.
Error Classification ¶
Use ClassifyEndError on the End event's Error field to distinguish client disconnects (context.Canceled), deadline exhaustion, write failures, and handler panics. Backends use this to set span status codes and metric labels.
Index ¶
- func AddGroup(ctx context.Context, prefix string)
- func DefaultOperationName(info *RequestTagInfo) string
- func InjectTags(ctx context.Context, tags *Tags) context.Context
- func ServerConnState(h Handler) func(net.Conn, http.ConnState)
- func ServerHandler(base http.Handler, opts ...ServerOption) http.Handler
- func SetError(ctx context.Context, err error)
- func SetRoute(ctx context.Context, pattern string)
- type Begin
- type ClientOption
- type ClientTransport
- type ConnBegin
- type ConnEnd
- type ConnStats
- type ConnTagInfo
- type End
- type EndErrorKind
- type Handler
- type InData
- type InHeader
- type MultiHandler
- func (mh MultiHandler) HandleConn(ctx context.Context, stats ConnStats)
- func (mh MultiHandler) HandleRequest(ctx context.Context, stats RequestStats)
- func (mh MultiHandler) TagConn(ctx context.Context, info *ConnTagInfo) context.Context
- func (mh MultiHandler) TagRequest(ctx context.Context, info *RequestTagInfo) context.Context
- type NoopHandler
- type OutData
- type OutHeader
- type RequestStats
- type RequestTagInfo
- type Route
- type ServerOption
- type Tags
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddGroup ¶
AddGroup records that the request entered a router group mounted at prefix. Nested groups accumulate: AddGroup("/api") then AddGroup("/v1") yields "/api/v1". It is a no-op when ctx carries no ServerHandler state, so routers can call it unconditionally.
func DefaultOperationName ¶
func DefaultOperationName(info *RequestTagInfo) string
DefaultOperationName returns the operation name. Precedence:
- info.OperationName if explicitly set
- info.RequestPattern if available: a. Used directly if it already contains a space (e.g. "GET /users/{id}") b. Prefixed with method otherwise (e.g. "/users/{id}" → "GET /users/{id}")
- "HTTP {method}" as final fallback
func InjectTags ¶
InjectTags places a Tags container into the context.
func ServerConnState ¶
ServerConnState returns a function for http.Server.ConnState that fires ConnBegin and ConnEnd for each connection lifecycle.
srv.ConnState = httpstats.ServerConnState(myHandler)
func ServerHandler ¶
func ServerHandler(base http.Handler, opts ...ServerOption) http.Handler
ServerHandler wraps an http.Handler with the full request lifecycle:
TagRequest → Begin → InHeader → InData* → OutHeader → OutData* → End
If the wrapped handler panics, End fires with a panic error and the panic is re-raised untouched, so net/http (and any recovery middleware above) behaves exactly as without the wrapper, including for http.ErrAbortHandler. A handler that returns without writing gets an OutHeader for the implicit 200.
The ResponseWriter handed to the handler keeps http.Flusher, http.Hijacker and http.Pusher if and only if the server's writer has them, and also works with http.ResponseController.
Types ¶
type ClientOption ¶
type ClientOption func(*clientConfig)
func WithClientHandler ¶
func WithClientHandler(h ...Handler) ClientOption
WithClientHandler sets the stats handler. Multiple handlers are composed via MultiHandler so each receives every event.
func WithClientNameFunc ¶
func WithClientNameFunc(f func(*RequestTagInfo)) ClientOption
WithClientNameFunc sets a function that populates RequestTagInfo.OperationName.
func WithClientTransport ¶
func WithClientTransport(rt http.RoundTripper) ClientOption
WithClientTransport sets the base RoundTripper. Defaults to http.DefaultTransport.
type ClientTransport ¶
type ClientTransport struct {
// contains filtered or unexported fields
}
ClientTransport wraps http.RoundTripper with the full request lifecycle:
TagRequest → Begin → OutHeader → OutData* → InHeader → InData* → End
Uses httptrace for low-level connection events. On RoundTrip error, the response body is drained for connection reuse and End fires with the error.
func NewClientTransport ¶
func NewClientTransport(opts ...ClientOption) *ClientTransport
NewClientTransport creates a ClientTransport. Defaults to NoopHandler and http.DefaultTransport.
type ConnBegin ¶
type ConnBegin struct {
Client bool
StartTime time.Time
RemoteAddr string
DNSDuration time.Duration // non-zero only on cold connections
TCPDuration time.Duration // non-zero only on cold connections
TLSDuration time.Duration // non-zero only on cold connections
}
ConnBegin is emitted when a new connection is established. On reused connections (pool hit), DNSDuration, TCPDuration, and TLSDuration are zero. On cold connections, they capture the cost of establishing the link — useful for isolating P99 latency spikes caused by DNS flapping, cross-region TCP handshake latency, or overloaded TLS termination.
type ConnStats ¶
type ConnStats interface {
// contains filtered or unexported methods
}
ConnStats is the sealed interface for connection-level statistics.
type ConnTagInfo ¶
type End ¶
End carries the final outcome of a request. Error is nil on success. Use ClassifyEndError to categorize the error for span status / labels.
Server only: Route is where the request landed, as recorded by routers through AddGroup and SetRoute, falling back to http.Request.Pattern for plain http.ServeMux routing; HandlerError is the error a handler reported through SetError. Both are final, unlike what TagRequest could see.
type EndErrorKind ¶
type EndErrorKind int
EndErrorKind categorizes the error on an End event.
const ( EndErrorNone EndErrorKind = iota EndErrorCanceled // context.Canceled (client disconnect) EndErrorDeadline // context.DeadlineExceeded or net.Error Timeout EndErrorWrite // write failure (broken pipe, reset) EndErrorRead // read failure EndErrorPanic // handler panic EndErrorOther // unclassified )
func ClassifyEndError ¶
func ClassifyEndError(err error) EndErrorKind
ClassifyEndError categorizes the error on an End event. A nil error returns EndErrorNone. Unwraps error chains via errors.Is and errors.As so wrapped context errors are detected.
type Handler ¶
type Handler interface {
TagConn(ctx context.Context, info *ConnTagInfo) context.Context
HandleConn(ctx context.Context, stats ConnStats)
TagRequest(ctx context.Context, info *RequestTagInfo) context.Context
HandleRequest(ctx context.Context, stats RequestStats)
}
Handler defines the interface for HTTP statistics collection.
Implementations must be safe for concurrent use: HandleRequest may be called concurrently for InData/OutData events under HTTP/2 full-duplex.
Context flow:
TagConn(ctx) → ctx'
└─ TagRequest(ctx') → ctx''
└─ HandleRequest(ctx'', ...)
└─ HandleConn(ctx', ...)
type InData ¶
InData fires for each chunk read from the request body (server) or response body (client). When Error is non-nil (excluding io.EOF), the read ended abnormally.
type InHeader ¶
type InHeader struct {
Client bool
Header http.Header
ContentLength int64
StatusCode int
Method string
TTFB time.Duration // client only: time from request body finish to first response byte
}
InHeader fires when response headers arrive (client) or request headers are received (server). On the client side, TTFB measures the time from the last byte of the request body to the first byte of the response — the round-trip transit plus server routing/queuing time. Zero on the server side.
type MultiHandler ¶
type MultiHandler []Handler
MultiHandler composes multiple Handler instances into one. TagConn and TagRequest are called in order, threading the context. HandleConn and HandleRequest are called on all handlers. An empty MultiHandler is a no-op.
This lets you combine backends — e.g. OTEL for tracing and Prometheus for metrics — without either knowing about the other:
httpstats.MultiHandler{otelHandler, promHandler}
func (MultiHandler) HandleConn ¶
func (mh MultiHandler) HandleConn(ctx context.Context, stats ConnStats)
func (MultiHandler) HandleRequest ¶
func (mh MultiHandler) HandleRequest(ctx context.Context, stats RequestStats)
func (MultiHandler) TagConn ¶
func (mh MultiHandler) TagConn(ctx context.Context, info *ConnTagInfo) context.Context
func (MultiHandler) TagRequest ¶
func (mh MultiHandler) TagRequest(ctx context.Context, info *RequestTagInfo) context.Context
type NoopHandler ¶
type NoopHandler struct{}
NoopHandler is a Handler whose methods are all no-ops.
func (NoopHandler) HandleConn ¶
func (NoopHandler) HandleConn(_ context.Context, _ ConnStats)
func (NoopHandler) HandleRequest ¶
func (NoopHandler) HandleRequest(_ context.Context, _ RequestStats)
func (NoopHandler) TagConn ¶
func (NoopHandler) TagConn(ctx context.Context, _ *ConnTagInfo) context.Context
func (NoopHandler) TagRequest ¶
func (NoopHandler) TagRequest(ctx context.Context, _ *RequestTagInfo) context.Context
type OutData ¶
OutData fires for each chunk written to the response body (server) or request body (client). When Error is non-nil, the write ended abnormally.
type OutHeader ¶
OutHeader fires when response headers are written (server) or request headers are sent (client). StatusCode is zero on the client side.
type RequestStats ¶
type RequestStats interface {
// contains filtered or unexported methods
}
RequestStats is the sealed interface for request-level statistics.
type RequestTagInfo ¶
type RequestTagInfo struct {
Client bool
Method string
Host string
URL *url.URL
OperationName string // defaults to "HTTP {method}" if empty
RequestPattern string // http.Request.Pattern (Go 1.22+)
// Server only. Proto is the request protocol ("HTTP/1.1", "HTTP/2.0"),
// Scheme is "https" when the connection is TLS and "http" otherwise (it
// never trusts forwarding headers), and RemoteAddr is the peer address.
Proto string
Scheme string
RemoteAddr string
// Header is the request's header map, which lets a handler do context
// propagation in TagRequest, where it also starts its span.
//
// Client: the header of the outgoing request. ClientTransport hands the
// handler a private clone, so setting values (for example injecting trace
// context) changes what is sent without mutating the caller's request.
// Server: the header of the incoming request, for extracting an upstream
// trace context. Handlers must not modify it.
Header http.Header
}
type Route ¶
type Route struct {
// Group is the prefix of the router group that took the request, such as
// "/users" or "/auth". It is set even when no route inside the group
// matched (a 404 or 405), so unmatched traffic is still attributable.
Group string
// Pattern is the full templated route, group included, for example
// "/users/{id}". Empty when nothing matched.
Pattern string
}
Route describes where a server request landed. Both fields are templates and therefore low-cardinality: they never contain a concrete URL path such as "/users/1234".
type ServerOption ¶
type ServerOption func(*serverConfig)
func WithServerHandler ¶
func WithServerHandler(h ...Handler) ServerOption
WithServerHandler sets the stats handler for the middleware. Multiple handlers are composed via MultiHandler so each receives every event.
func WithServerNameFunc ¶
func WithServerNameFunc(f func(*RequestTagInfo)) ServerOption
WithServerNameFunc sets a function that populates RequestTagInfo.OperationName.
httpstats.ServerHandler(mux, h,
httpstats.WithServerNameFunc(func(info *httpstats.RequestTagInfo) {
info.OperationName = info.Method + " " + routePattern
}),
)
type Tags ¶
type Tags struct {
// contains filtered or unexported fields
}
Tags is a thread-safe container for low-cardinality telemetry labels discovered mid-flight. It is injected into the request context by the middleware and can be enriched by downstream handlers.
func myHandler(w http.ResponseWriter, r *http.Request) {
if tags := httpstats.FromContext(r.Context()); tags != nil {
tags.Set("tenant_id", extractTenant(r))
}
}
func FromContext ¶
FromContext extracts the Tags container injected by InjectTags. Returns nil if no Tags are present.
func (*Tags) Get ¶
Get retrieves the value for key. The boolean indicates whether the key was present. Safe for concurrent use.