Documentation
¶
Overview ¶
Package middleware provides net/http middleware for sqi-server.
Middleware in this package is router-agnostic: each function returns a standard func(http.Handler) http.Handler that can be composed directly or mounted via any router (chi, gorilla/mux, net/http ServeMux, etc.).
Index ¶
- func APIVersion(version string) func(http.Handler) http.Handler
- func Auth(authn auth.Authenticator, logger *slog.Logger) func(http.Handler) http.Handler
- func CSRF(cfg CSRFConfig, logger *slog.Logger) func(http.Handler) http.Handler
- func Deprecated(declaredAt, sunsetDate time.Time, link string) func(http.Handler) http.Handler
- func RateLimit(cfg RateLimitConfig, logger *slog.Logger) func(http.Handler) http.Handler
- func RequestIDFromContext(ctx context.Context) string
- func RequestLogger(logger *slog.Logger) func(http.Handler) http.Handler
- func RequestMetrics(m *metrics.Metrics) func(http.Handler) http.Handler
- func Standby(isLeader func() bool, leaderName func() string, probes []string) func(http.Handler) http.Handler
- func WriteProblem(w http.ResponseWriter, r *http.Request, status int, detail string)
- type CSRFConfig
- type RateLimitConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func APIVersion ¶
APIVersion returns middleware that sets the X-API-Version response header on every response so clients can verify which version of the sqi API they are talking to without inspecting the URL.
The header is added to the response map before the inner handler runs, so it is present even on error responses. Go's net/http flushes all headers that were Set/Add before the first Write or WriteHeader call, which is why setting headers prior to calling next.ServeHTTP is the correct pattern here.
Usage (applied to a chi sub-router):
r.Route("/api/v1", func(api chi.Router) {
api.Use(middleware.APIVersion("1"))
// … routes …
})
func Auth ¶ added in v0.3.0
Auth returns middleware that authenticates each request via authn and injects the resulting auth.Principal into the request context. On authentication failure it short-circuits with a 401 RFC 7807 problem-details response and does not call the wrapped handler.
A nil authn is treated as auth.Anonymous() (auth disabled), so every request receives the anonymous superuser principal and behavior is unchanged.
Mount it on the REST resource routes only (not /ws, which is gated by its own upgrade hook, and not the public probes on the root router).
func CSRF ¶ added in v0.3.0
CSRF returns middleware enforcing the policy described in the package-level doc comment above.
func Deprecated ¶
Deprecated returns middleware that marks an endpoint as deprecated by injecting the standard HTTP deprecation headers defined in RFC 8594.
Headers set:
- Deprecation: <RFC 7231 HTTP-date> — when the deprecation was declared. Use time.Time zero value to emit "true" instead of a date, which is valid per the RFC when the declaration date is not meaningful.
- Sunset: <RFC 7231 HTTP-date> — when the endpoint will be removed. Omitted when sunsetDate is the zero value.
- Link: <link>; rel="deprecation" — URL of documentation describing the deprecation and migration path. Omitted when link is empty. link must be a valid absolute URL; a syntactically invalid value (e.g. one containing an unescaped '>') will produce a malformed Link header.
Wrap individual handlers (not an entire route group) with Deprecated so that only the specific endpoints that are being retired carry these headers.
Both chi usage patterns work:
// Pattern 1: inline wrap
api.Get("/v1/old-endpoint", middleware.Deprecated(
time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC),
time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC),
"https://docs.sqi.dev/api/deprecations#old-endpoint",
)(oldHandler))
// Pattern 2: chi.With (preferred when combining multiple per-route middleware)
api.With(middleware.Deprecated(
time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC),
time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC),
"https://docs.sqi.dev/api/deprecations#old-endpoint",
)).Get("/v1/old-endpoint", oldHandler)
func RateLimit ¶
RateLimit returns middleware that enforces a per-IP token-bucket rate limit. Clients that exceed the limit receive HTTP 429 Too Many Requests with an RFC 7807 problem-details body (matching every other error on the API surface) and a delta-seconds Retry-After header derived from the bucket's refill rate.
Each remote IP maintains its own bucket; buckets are allocated lazily on first request. Rejected requests return their reserved token (best-effort under concurrent rejections — see Reservation.Cancel), so being rejected does not push a client's recovery time out further.
Limitations:
No LRU eviction: the limiter map grows unbounded. This is acceptable for trusted local deployments where the client IP space is small.
RemoteAddr only: when a reverse proxy is in front, all clients share the proxy's IP and effectively one bucket. X-Forwarded-For / X-Real-IP are not honored.
Usage (applied to the /api/v1 sub-router):
api.Use(middleware.RateLimit(middleware.RateLimitConfig{
RequestsPerSecond: 20,
Burst: 40,
}, logger))
func RequestIDFromContext ¶
RequestIDFromContext returns the request ID attached to ctx by RequestLogger, or an empty string if ctx carries no request ID.
func RequestLogger ¶
RequestLogger returns middleware that, for every request:
- Reads the X-Request-ID header; if absent, generates a random 16-char hex ID using crypto/rand.
- Stores the request ID in the request context (retrieve with RequestIDFromContext).
- Echoes the request ID in the X-Request-ID response header.
- Wraps the http.ResponseWriter to capture the status code.
- After the handler returns, logs method, path, status code, duration, and request ID at Info level using the provided *slog.Logger.
WebSocket upgrades (HTTP 101) are handled transparently: the wrapped writer implements http.Hijacker so the upgrade handshake proceeds normally, and the middleware logs the 101 status after the connection is hijacked.
func RequestMetrics ¶
RequestMetrics returns middleware that records Prometheus metrics for every HTTP request:
- sqi_http_requests_total — counter incremented after the handler returns, labeled by method, path, and status code.
- sqi_http_request_duration_seconds — histogram observed after the handler returns, labeled by method and path.
The "path" label is the chi route pattern that served the request, such as /api/v1/jobs/{id}, so the number of series is bounded by the routes, not by the IDs requested. A request a sub-router answered without matching one of its routes carries the sub-router's mount pattern (/api/v1/* for an unknown API path or a rate-limited request, /* for the UI catch-all). The "method" label is the request method, or OTHER for a non-standard one. RequestMetrics must be mounted on a chi router: the pattern is read from the request's chi route context after the handler returns.
func Standby ¶ added in v0.4.0
func Standby(isLeader func() bool, leaderName func() string, probes []string) func(http.Handler) http.Handler
Standby returns middleware for a server in a high-availability group. While isLeader reports false it answers every request other than probes, the paths a standby still serves (the probes a supervisor or load balancer reads, and its metrics, matched exactly), with 503, Retry-After: 2 and {"error":"standby","leader":"<name>"}, where the name is leaderName's, "" when no leader is known. Nothing is proxied to the leader: a balancer health-checking /leaderz routes there itself.
Both functions are read on every request, so a promotion opens the API without rebuilding the router.
func WriteProblem ¶
WriteProblem writes an RFC 7807 problem-details response. It sets Content-Type: application/problem+json and the given HTTP status, then encodes a problemDetail body. detail should be a short, user-facing explanation of what went wrong.
Types ¶
type CSRFConfig ¶ added in v0.3.0
type CSRFConfig struct {
// CookieName is the session cookie whose presence marks a request as
// cookie-authenticated (and therefore CSRF-relevant). Mirrors
// api.Deps.CookieName / config.AuthConfig.Session.CookieName.
CookieName string
// AllowedOrigins are additional acceptable Origin values for
// cookie-authenticated cross-origin mutations, beyond same-origin (which
// is always allowed). Typically cfg.CORSOrigins.
AllowedOrigins []string
}
CSRFConfig configures the Origin-based CSRF guard.
type RateLimitConfig ¶
type RateLimitConfig struct {
// RequestsPerSecond is the steady-state refill rate for each IP bucket.
// Defaults to 20 when zero.
RequestsPerSecond rate.Limit
// Burst is the maximum number of requests allowed in a single instant.
// Defaults to 40 when zero.
Burst int
}
RateLimitConfig controls the per-IP token-bucket parameters.