Documentation
¶
Overview ¶
Package middlewares provides Gin HTTP middleware for cross-cutting concerns: recovery, tracing, logging, metrics, timeout, CORS, auth, and rate limiting.
Role in architecture:
- Adapters: sit between the HTTP server and handlers; no business logic, only request/response and infra calls.
Responsibilities:
- Recovery: catch panics, log stack, return JSON 500.
- Tracing: inject request/trace/correlation IDs from headers or generate UUIDs; store in context for logger.
- Logging: log each request (method, path, status, latency, IP) with context-bound logger.
- Metrics: expose Prometheus counters, histogram, and in-flight gauge (route pattern as label).
- Timeout: set request context deadline so downstream DB/Redis respect it.
- CORS: set Access-Control-* headers from config.
- Auth: validate Bearer JWT via jwt.TokenVerifier (Manager or Verifier); set user_id and impersonation fields in context. Use AuthMiddleware(verifier) with jwt.NewManager or jwt.NewVerifier for verification-only services.
- Rate limiting: Redis sliding-window (ZSET + Lua); 429 when exceeded; skip paths configurable.
Constraints:
- Rate limiter requires Redis enabled and config.RateLimiter.Enabled; fails open on Redis error.
- Auth requires a non-nil jwt.TokenVerifier (*jwt.Manager or *jwt.Verifier); pass it to AuthMiddleware(verifier).
- No provider switching or fallbacks inside middleware; config is read once at middleware build.
This package must NOT:
- Contain use-case or domain logic; only HTTP and infra concerns.
Index ¶
- Constants
- func AuthMiddleware(verifier jwt.TokenVerifier) gin.HandlerFunc
- func CORS() gin.HandlerFunc
- func LoggerMiddleware() gin.HandlerFunc
- func Metrics() gin.HandlerFunc
- func NoMethodHandler() gin.HandlerFunc
- func NoRouteHandler() gin.HandlerFunc
- func RateLimiter() gin.HandlerFunc
- func RecoveryHandler(ctx *gin.Context)
- func RequestID() gin.HandlerFunc
- func RequestTimeout(d time.Duration) gin.HandlerFunc
- func TraceMiddleware() gin.HandlerFunc
Constants ¶
const ( HeaderTraceID = "X-Trace-Id" HeaderCorrelationID = "X-Correlation-Id" HeaderRequestID = "X-Request-Id" )
HeaderTraceID, HeaderCorrelationID, and HeaderRequestID are the HTTP header names used for trace and correlation IDs.
Variables ¶
This section is empty.
Functions ¶
func AuthMiddleware ¶
func AuthMiddleware(verifier jwt.TokenVerifier) gin.HandlerFunc
AuthMiddleware returns a Gin middleware that validates the Authorization: Bearer <token> header using the given JWT verifier (Manager or Verifier), and sets identity information in the Gin context. Pass a *jwt.Manager (from jwt.NewManager) or *jwt.Verifier (from jwt.NewVerifier) for verification-only services. Verifier must not be nil.
func CORS ¶
func CORS() gin.HandlerFunc
CORS returns a Gin middleware that sets Access-Control-* headers from config. If Cors.Global is true it sets Allow-Origin to "*"; otherwise to Cors.Ips. Responds to OPTIONS with 204.
func LoggerMiddleware ¶ added in v0.1.7
func LoggerMiddleware() gin.HandlerFunc
LoggerMiddleware returns a Gin middleware that logs each request after Next(): method, path, status, latency, client IP, user-agent. Uses logger.WithContext(ctx) so trace_id and correlation_id appear in JSON when RequestID or TraceMiddleware is used. Log level: 5xx Error, 4xx Warn, 2xx/3xx Info.
func Metrics ¶ added in v0.3.0
func Metrics() gin.HandlerFunc
Metrics returns a Gin middleware that exposes Prometheus HTTP metrics:
- http_requests_total (counter, labels: method, path, status)
- http_request_duration_seconds (histogram, labels: method, path, status)
- http_requests_in_flight (gauge)
Register the /metrics endpoint separately using promhttp.Handler().
func NoMethodHandler ¶
func NoMethodHandler() gin.HandlerFunc
NoMethodHandler returns a handler that responds with 405 Method Not Allowed and a standardized JSON body.
func NoRouteHandler ¶
func NoRouteHandler() gin.HandlerFunc
NoRouteHandler returns a handler that responds with 404 and a standardized JSON body for unmatched routes.
func RateLimiter ¶ added in v0.1.7
func RateLimiter() gin.HandlerFunc
RateLimiter returns a Gin middleware that enforces a sliding-window rate limit using Redis. Key is per IP or per user (from "admin_id" in context when KeyBy is "user"). SkipPaths (comma-separated) are not counted. On exceed returns 429 with Retry-After and X-RateLimit-* headers. If config.RateLimiter.Enabled or config.Redis.Enabled is false, returns a no-op middleware. On Redis error allows the request (fail open).
func RecoveryHandler ¶
RecoveryHandler is a Gin handler that recovers from panics, logs the stack trace, and responds with a 500 JSON body. It must be registered with gin.Use(RecoveryHandler) (no parentheses; it is a HandlerFunc, not a factory).
func RequestID ¶ added in v0.2.1
func RequestID() gin.HandlerFunc
RequestID returns Gin middleware that ensures a request/correlation ID on every request. It reads X-Request-ID or X-Trace-ID from headers; generates a new UUID if missing. The ID is stored in context (trace_id and correlation_id) so logger.WithContext and LoggerMiddleware include it in structured logs. Response headers X-Request-ID and X-Trace-ID are set for client correlation.
func RequestTimeout ¶ added in v0.3.0
func RequestTimeout(d time.Duration) gin.HandlerFunc
RequestTimeout returns a middleware that sets a deadline on the request context. Handlers and use cases that pass this context to repositories will have queries bounded by the timeout; when the timeout is exceeded, context is cancelled and operations should return context.DeadlineExceeded. Use after trace/request-id so the timeout applies to the full handler chain.
func TraceMiddleware ¶ added in v0.1.11
func TraceMiddleware() gin.HandlerFunc
TraceMiddleware returns a Gin middleware that reads X-Trace-Id and X-Correlation-Id (or X-Request-Id for trace), stores them in the request context via logger.WithTraceID/WithCorrelationID, and echoes them in response headers. If trace ID is missing, generates a UUID. Use when upstream sends distinct trace and correlation IDs.
Types ¶
This section is empty.