httpstats

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

httpstats

Backend-agnostic net/http observability — single interface, any telemetry backend. Modeled after gRPC-Go's stats.Handler. Zero dependencies beyond the standard library.

go get github.com/piusalfred/httpstats

Quick start

Write a handler that implements httpstats.Handler (see the reference implementations for OpenTelemetry and Prometheus), then wire it in:

// Server middleware
wrapped := httpstats.ServerHandler(mux, httpstats.WithServerHandler(myHandler))
http.ListenAndServe(":8080", wrapped)

// Client transport
ct := httpstats.NewClientTransport(httpstats.WithClientHandler(myHandler))
client := &http.Client{Transport: ct}

Combine multiple backends:

httpstats.ServerHandler(mux, httpstats.WithServerHandler(otelHandler, promHandler))

Event lifecycle

Server: TagRequest → Begin → InHeader → InData* → OutHeader → OutData* → End
Client: TagRequest → Begin → OutHeader → OutData* → InHeader → InData* → End

Connection events (TagConn → HandleConn) fire independently.

Context propagation

RequestTagInfo.Header is the request header seen in TagRequest, where a handler also starts its span. On the client it is a private clone of the outgoing request's header, so injecting trace context there changes what is sent without mutating the caller's request. On the server it is the incoming header, for extracting an upstream trace context; do not modify it.

func (h *tracing) TagRequest(ctx context.Context, info *httpstats.RequestTagInfo) context.Context {
    if !info.Client {
        ctx = propagator.Extract(ctx, propagation.HeaderCarrier(info.Header))
    }
    ctx, span := tracer.Start(ctx, httpstats.DefaultOperationName(info))
    if info.Client {
        propagator.Inject(ctx, propagation.HeaderCarrier(info.Header))
    }
    return context.WithValue(ctx, spanKey{}, span)
}

Server routing and std-lib behavior

Routers report where a request landed so recorders can label it without using the concrete URL path:

httpstats.AddGroup(ctx, "/users")   // router group prefix, accumulates when nested
httpstats.SetRoute(ctx, "/{id}")    // template relative to the group -> "/users/{id}"
httpstats.SetError(ctx, err)        // handler error returned by value

End.Route and End.HandlerError carry the final values (http.Request.Pattern stands in when no group took the request). All three helpers are no-ops outside ServerHandler.

ServerHandler stays transparent to net/http: the writer it passes on keeps http.Flusher, http.Hijacker and http.Pusher exactly when the real one has them and works with http.ResponseController; a handler that writes nothing still gets an OutHeader for the implicit 200; panics are reported through End and re-raised untouched, including http.ErrAbortHandler.

Packages

Path Purpose
httpstats Core interface, stats types, middleware, transport
docs/ Reference implementations for OTEL and Prometheus

Development

bash tools/setup.sh   # install gotools, sync tools
make hooks            # install pre-commit hooks

Tools are managed via gotools.

Make targets

Command Does
make fmt go mod tidy, license headers, YAML, Go imports
make lint golangci-lint (no fixes)
make fix go fix + lint --fix + fmt
make test Tests with race detector and coverage
make ci Build + fmt + lint + vet + test + vulncheck + mdlint
make hooks Install and run pre-commit hooks
make tidy go mod tidy
make cover Tests with coverage profile output
make bench Run benchmarks

Pre-commit

On every commit, lefthook runs:

  • fmt — formats Go files, stages the result
  • check — golangci-lint + go vet
  • test — full test suite with race detector

License

MIT

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddGroup

func AddGroup(ctx context.Context, prefix string)

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:

  1. info.OperationName if explicitly set
  2. 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}")
  3. "HTTP {method}" as final fallback

func InjectTags

func InjectTags(ctx context.Context, tags *Tags) context.Context

InjectTags places a Tags container into the context.

func ServerConnState

func ServerConnState(h Handler) func(net.Conn, http.ConnState)

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.

func SetError

func SetError(ctx context.Context, err error)

SetError records an application-level error returned by a handler that reports failures by value instead of writing them, so the recorder can attach it to the span and log line. The first error wins. No-op without ServerHandler state or for a nil error.

func SetRoute

func SetRoute(ctx context.Context, pattern string)

SetRoute records the matched route template, relative to the groups entered so far: after AddGroup("/users"), SetRoute("/{id}") gives "/users/{id}". The last call wins. No-op without ServerHandler state.

Types

type Begin

type Begin struct {
	Client    bool
	StartTime time.Time
}

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.

func (*ClientTransport) RoundTrip

func (ct *ClientTransport) RoundTrip(req *http.Request) (*http.Response, error)

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 ConnEnd

type ConnEnd struct {
	Client bool
	Error  error
}

type ConnStats

type ConnStats interface {
	// contains filtered or unexported methods
}

ConnStats is the sealed interface for connection-level statistics.

type ConnTagInfo

type ConnTagInfo struct {
	Client     bool
	RemoteAddr net.Addr
	LocalAddr  net.Addr
	TLS        *tls.ConnectionState
}

type End

type End struct {
	Client       bool
	EndTime      time.Time
	Error        error
	Route        Route
	HandlerError error
}

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

type InData struct {
	Client bool
	Length int
	Error  error
}

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) TagRequest

type OutData

type OutData struct {
	Client bool
	Length int
	Error  error
}

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

type OutHeader struct {
	Client        bool
	Header        http.Header
	ContentLength int64
	StatusCode    int
}

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

func FromContext(ctx context.Context) *Tags

FromContext extracts the Tags container injected by InjectTags. Returns nil if no Tags are present.

func NewTags

func NewTags() *Tags

NewTags creates a Tags container.

func (*Tags) Get

func (t *Tags) Get(key string) (string, bool)

Get retrieves the value for key. The boolean indicates whether the key was present. Safe for concurrent use.

func (*Tags) Range

func (t *Tags) Range(fn func(key, value string) bool)

Range calls fn for each key-value pair. Iteration stops if fn returns false. Safe for concurrent use.

func (*Tags) Set

func (t *Tags) Set(key, value string)

Set stores a key-value pair. Safe for concurrent use.

Jump to

Keyboard shortcuts

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