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.
- MTLS: require verified TLS client certificate when config.MTLS.Enabled; set mtls_client_cn in context; skip paths from MTLS_SKIP_PATHS.
- 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 CloudTraceMiddleware() gin.HandlerFunc
- func HTTPInstrumentation() gin.HandlerFunc
- func LoggerMiddleware() gin.HandlerFunc
- func MTLSMiddleware() gin.HandlerFunc
- func Metrics() gin.HandlerFunc
- func NoMethodHandler() gin.HandlerFunc
- func NoRouteHandler() gin.HandlerFunc
- func ParseCloudTraceContext(header string) (traceID, spanID string, ok bool)
- 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 ( HeaderCloudTraceContext = "X-Cloud-Trace-Context" HeaderTraceID = "X-Trace-Id" HeaderCorrelationID = "X-Correlation-Id" HeaderRequestID = "X-Request-Id" )
GCP format: X-Cloud-Trace-Context: TRACE_ID/SPAN_ID;o=TRACE_TRUE See: https://cloud.google.com/trace/docs/setup#force-trace
const (
// ContextMTLSClientCN is the verified client certificate Common Name.
ContextMTLSClientCN = "mtls_client_cn"
)
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 it reflects the request Origin when it matches Cors.Frontend or an entry in Cors.Ips. Responds to OPTIONS with 204.
func CloudTraceMiddleware ¶ added in v0.4.1
func CloudTraceMiddleware() gin.HandlerFunc
CloudTraceMiddleware returns Gin middleware that extracts X-Cloud-Trace-Context, X-Request-ID, and X-Correlation-ID, injects traceID/spanID/correlationID into context, and echoes headers. Correlation ID is never overwritten when already set (business transaction ID).
func HTTPInstrumentation ¶ added in v0.4.1
func HTTPInstrumentation() gin.HandlerFunc
HTTPInstrumentation returns Gin middleware that captures request/response metrics and injects a GCP-format httpRequest into context so every log in the request includes it. Place after CloudTraceMiddleware or TraceMiddleware.
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, span_id, correlation_id, and httpRequest (if HTTPInstrumentation ran) appear in JSON. Log level: 5xx Error, 4xx Warn, 2xx/3xx Info. Register after CloudTraceMiddleware (or TraceMiddleware) and HTTPInstrumentation for full GCP fields.
func MTLSMiddleware ¶ added in v0.5.2
func MTLSMiddleware() gin.HandlerFunc
MTLSMiddleware returns Gin middleware that requires a verified TLS client certificate when config.MTLS.Enabled is true. Skips paths listed in MTLS_SKIP_PATHS. Use with mtls.ConfigureServer so the listener verifies client certs at the TLS layer.
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 ParseCloudTraceContext ¶ added in v0.4.1
ParseCloudTraceContext parses X-Cloud-Trace-Context header. Format: TRACE_ID/SPAN_ID;o=TRACE_TRUE (o=1 means sampled). Returns traceID, spanID, and whether the header was present.
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 recovers from panics, logs structured CRITICAL with trace/correlation preserved, and responds with 500. Register with gin.Use(RecoveryHandler). Do not use for fatal errors in request context; use logger.Errorf + abort.
func RequestID ¶ added in v0.2.1
func RequestID() gin.HandlerFunc
RequestID returns Gin middleware that ensures a request/correlation ID on every request. Prefer CloudTraceMiddleware for full GCP trace integration; use RequestID for minimal setup.
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 Gin middleware that reads X-Trace-Id, X-Correlation-Id, X-Request-Id, and optionally X-Cloud-Trace-Context. Correlation ID is never overwritten when already set.
Types ¶
This section is empty.