middleware

package
v0.18.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package middleware provides standard net/http server middleware for skit services.

It covers the cross-cutting concerns most HTTP services need: panic recovery, the server span, structured access logging, request timeouts, body-size limits, CORS, security headers, response compression, and request-id echo. Every middleware has the signature func(http.Handler) http.Handler (aliased as Middleware), so it composes with router.Use, router.With, and go-pkgz/routegroup. Because Trace puts the server span into the request context, an AccessLog over a logger built by package logger writes trace_id on every line.

These are the transport layer of the two-layer model (see the router package): they wrap the encoded response and every route — including raw http.Handlers and the typed rest boundary — via router.Use / router.With. Concerns that need the typed ResponseEncoder a handler returns (auth, validation, error localization) belong instead in the application layer as rest.MidFunc (router.UseApp / WithApp / per-route).

Ordering

Panics goes on the root router, so it wraps everything. The rest wraps the business routes only, in a group made with router.With: Trace first, after routing, so the span is named after the route pattern; then AccessLog, then the limit/timeout guards. Technical routes — probes, metrics, pprof — stay outside the group: they get no span, no access-log line and no timeout.

r := router.New(appMids...)
r.Use(middleware.Panics(log)) // recover -> 500, log stack
api := r.With(
	// server span per request, named after the route
	middleware.Trace(middleware.TraceConfig{TracerProvider: tp}),
	middleware.AccessLog(log),         // one structured line per request
	middleware.SizeLimit(1<<20),       // cap request body at 1 MiB
	middleware.Timeout(5*time.Second), // cancel ctx after 5s
)

Middleware

  • Panics(log): recover from panics, log the stack, respond 500. A nil log skips logging. http.ErrAbortHandler is panicked again for net/http.
  • Trace(cfg): open the server span of the request with otelhttp, named "{METHOD} {route}", continuing the incoming W3C trace context, and return the span's traceparent in the response. TraceConfig.TracerProvider nil means the global provider; TraceConfig.Public marks requests from outside the trust boundary, whose span starts a new trace linked to the caller's.
  • SetRoute(r, route): name the server span after route, for a handler that routes by itself below Trace (a grpc-gateway mux mounted on a prefix).
  • Route(r), Method(r): the route template and the method as the span, the access log and the HTTP metrics label a request: the route SetRoute recorded, else the pattern that matched; a standard method, else _OTHER.
  • AccessLog(log): emit one structured line per request using OpenTelemetry HTTP semantic-convention field names. A nil log skips logging.
  • Timeout(d): cancel the request context after d; a non-positive d disables it (returns next unchanged).
  • SizeLimit(n): cap the request body at n bytes via http.MaxBytesReader; a non-positive n disables it.
  • CORS(cfg): apply a cross-origin policy — set Access-Control-* headers on allowed origins and answer preflight OPTIONS with 204.
  • SecureHeaders(): set conservative security response headers (nosniff, frame-deny, no-referrer) without overriding ones a handler set.
  • Compress(): gzip responses when the client sends Accept-Encoding: gzip.
  • RequestID(): echo the correlation id (incoming X-Request-ID, else the trace id) in the X-Request-ID response header.

The last four are not part of the generated scaffold's default chain — wire them per service (CORS in particular needs a per-deployment origin policy).

Example

Panics goes on the root, so it wraps every route; the guards go on the group of business routes, so the probe gets none of them.

package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/assanoff/skit/middleware"
	"github.com/assanoff/skit/rest/router"
)

func main() {
	r := router.New()
	r.Use(middleware.Panics(nil))
	r.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	api := r.With(
		middleware.SecureHeaders(),
		middleware.RequestID(),
		middleware.SizeLimit(16),
	)
	api.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) {
		if _, err := io.ReadAll(r.Body); err != nil {
			http.Error(w, err.Error(), http.StatusRequestEntityTooLarge)
			return
		}
		w.WriteHeader(http.StatusCreated)
	})
	api.HandleFunc("GET /panic", func(http.ResponseWriter, *http.Request) {
		panic("nil map")
	})

	for _, req := range []*http.Request{
		httptest.NewRequest(http.MethodGet, "/healthz", nil),
		httptest.NewRequest(http.MethodPost, "/notes", strings.NewReader("short")),
		httptest.NewRequest(http.MethodPost, "/notes", strings.NewReader(strings.Repeat("x", 64))),
		httptest.NewRequest(http.MethodGet, "/panic", nil),
	} {
		req.Header.Set(middleware.RequestIDHeader, "req-1")
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		fmt.Printf("%s %s %d %q %q\n", req.Method, req.URL.Path, w.Code,
			w.Header().Get("X-Content-Type-Options"), w.Header().Get(middleware.RequestIDHeader))
	}
}
Output:
GET /healthz 200 "" ""
POST /notes 201 "nosniff" "req-1"
POST /notes 413 "nosniff" "req-1"
GET /panic 500 "nosniff" "req-1"

Index

Examples

Constants

View Source
const RequestIDHeader = "X-Request-ID"

RequestIDHeader is the header RequestID reads and echoes.

Variables

This section is empty.

Functions

func Method added in v0.14.0

func Method(r *http.Request) string

Method returns the method of r as the HTTP semantic conventions record it: one of the nine standard methods, upper-cased, else "_OTHER". The HTTP metrics label requests with it.

func Route added in v0.14.0

func Route(r *http.Request) string

Route returns the route of r as a template such as "/v1/widgets/{id}": the route SetRoute recorded, else r.Pattern without its method and host, else "" (a request outside a route group). The HTTP metrics label requests with it.

Example

Route and Method are the labels of a request in the span, the access log and the metrics: the route template, not the path. A handler that routes by itself below a prefix names its route with SetRoute, which Trace keeps for the middleware inside it.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/assanoff/skit/middleware"
	"github.com/assanoff/skit/rest/router"
)

func main() {
	label := func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			next.ServeHTTP(w, r)
			fmt.Println(middleware.Method(r), middleware.Route(r))
		})
	}
	gateway := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
		middleware.SetRoute(r, "/gw/v1/widgets/{id}")
	})

	r := router.New()
	api := r.With(middleware.Trace(middleware.TraceConfig{}), label)
	api.HandleFunc("GET /widgets/{id}", func(http.ResponseWriter, *http.Request) {
	})
	api.Handle("/gw/", gateway)

	r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/widgets/42", nil))
	r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("PURGE", "/gw/v1/widgets/7", nil))
}
Output:
GET /widgets/{id}
_OTHER /gw/v1/widgets/{id}

func SetRoute added in v0.14.0

func SetRoute(r *http.Request, route string)

SetRoute names the server span of r after route, for a handler that routes by itself below Trace: the span becomes "{METHOD} {route}" with http.route set to route, instead of the prefix the outer router matched, and Route reports it, so the HTTP metrics label the request with it too. route is a template such as "/v1/widgets/{id}", never the request path. Safe to call from any goroutine of the handler.

Types

type CORSConfig added in v0.6.0

type CORSConfig struct {
	// AllowedOrigins is the set of permitted Origin values, e.g.
	// {"https://app.example.com"}. The single entry "*" allows any origin.
	AllowedOrigins []string
	// AllowedMethods defaults to GET, QUERY, POST, PUT, PATCH, DELETE, OPTIONS.
	AllowedMethods []string
	// AllowedHeaders defaults to Origin, Content-Type, Accept, Authorization.
	AllowedHeaders []string
	// ExposedHeaders lists response headers the browser is allowed to read.
	ExposedHeaders []string
	// AllowCredentials sets Access-Control-Allow-Credentials. With credentials
	// the wildcard is never sent: the specific request Origin is echoed instead
	// (browsers reject "*" with credentials).
	AllowCredentials bool
	// MaxAge is the preflight cache lifetime in seconds (Access-Control-Max-Age).
	MaxAge int
}

CORSConfig configures the CORS middleware. The zero value allows no origins (every cross-origin request is passed through without CORS headers, so the browser blocks it) — set AllowedOrigins to opt in.

type Middleware

type Middleware = func(http.Handler) http.Handler

Middleware is standard net/http middleware.

func AccessLog

func AccessLog(log *slog.Logger) Middleware

AccessLog logs one structured line per request with the request's context. With a logger built by logger.New or logger.NewWithHandler, each line also carries the trace fields of the request's span.

func CORS added in v0.6.0

func CORS(cfg CORSConfig) Middleware

CORS returns middleware applying the policy in cfg. It sets the Access-Control-* headers on allowed cross-origin responses and answers the preflight OPTIONS request with 204. Requests without an Origin are passed through untouched; a request from a disallowed origin gets no CORS headers (so the browser blocks it), and a disallowed preflight is short-circuited with 204 and no Allow-* headers.

Example

CORS answers a preflight of an allowed origin with 204 and the Access-Control-* headers; another origin gets none, and the browser blocks it.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/assanoff/skit/middleware"
)

func main() {
	cors := middleware.CORS(middleware.CORSConfig{
		AllowedOrigins: []string{"https://app.example.com"},
		MaxAge:         600,
	})
	h := cors(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))

	for _, origin := range []string{"https://app.example.com", "https://evil.example"} {
		req := httptest.NewRequest(http.MethodOptions, "/widgets", nil)
		req.Header.Set("Origin", origin)
		req.Header.Set("Access-Control-Request-Method", http.MethodPost)
		w := httptest.NewRecorder()
		h.ServeHTTP(w, req)
		fmt.Printf("%d %q %q\n", w.Code,
			w.Header().Get("Access-Control-Allow-Origin"),
			w.Header().Get("Access-Control-Allow-Methods"))
	}
}
Output:
204 "https://app.example.com" "GET, QUERY, POST, PUT, PATCH, DELETE, OPTIONS"
204 "" ""

func Compress added in v0.6.0

func Compress() Middleware

Compress returns middleware that gzip-encodes responses when the client sends "Accept-Encoding: gzip". It sets Content-Encoding: gzip and Vary: Accept-Encoding, and drops the (now-wrong) Content-Length. Bodyless responses (1xx, 204, 304) are never encoded, and a handler that already set Content-Encoding is left alone. Flusher is preserved.

func Panics

func Panics(log *slog.Logger) Middleware

Panics recovers a panic, logs it once with the stack, and responds with 500. Register it once, outermost (router root Use), so it catches whatever the layers below it do not; an access log further in that recovers panics itself (httplog RecoverPanics) records the 500 first.

http.ErrAbortHandler is panicked again: it asks net/http to abort the response, not to answer it.

func RequestID added in v0.6.0

func RequestID() Middleware

RequestID echoes a request correlation id in the X-Request-ID response header. It reuses the client's incoming X-Request-ID when present; otherwise it falls back to the trace id of the request's span (so put it after Trace in the chain). It never overwrites an id a handler set itself. When no id is available it does nothing — it does not synthesize one (tracing owns id generation).

func SecureHeaders added in v0.6.0

func SecureHeaders() Middleware

SecureHeaders sets a conservative set of security response headers on every response — safe defaults for a JSON API:

X-Content-Type-Options: nosniff   // do not MIME-sniff the body
X-Frame-Options: DENY             // never framed (clickjacking)
Referrer-Policy: no-referrer      // do not leak the URL in Referer

It only sets a header when the handler has not already set it, so a handler that needs a different value (e.g. an endpoint meant to be embedded) wins.

func SizeLimit

func SizeLimit(n int64) Middleware

SizeLimit caps the request body at n bytes. A non-positive n disables it.

func Timeout

func Timeout(d time.Duration) Middleware

Timeout cancels the request context after d and (if nothing was written) lets downstream handlers observe ctx.Err. A non-positive d disables the middleware.

func Trace added in v0.14.0

func Trace(cfg TraceConfig) Middleware

Trace opens the server span of a request with otelhttp and writes its traceparent into the response (otel.InjectToResponse). The span continues the W3C trace context of the request and is named "{METHOD} {route}".

Put it into the group of business routes, after routing, so r.Pattern names the span, and first in that group: the access log, the metrics and the handler then run inside the span, and their log records carry its trace id. Routes outside the group (health, metrics, pprof) get no spans. HTTP metrics come from package metrics, so otelhttp records none.

A handler that routes by itself below Trace, such as a grpc-gateway mux mounted on a prefix, names the span after its own route with SetRoute.

type TraceConfig added in v0.14.0

type TraceConfig struct {
	// TracerProvider records the server spans; nil → the global provider.
	TracerProvider trace.TracerProvider
	// Public marks the requests of an untrusted edge: their span starts a new
	// trace with a link to the caller's instead of continuing it. nil → every
	// caller is trusted.
	Public func(*http.Request) bool
}

TraceConfig configures Trace.

Jump to

Keyboard shortcuts

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