Skip to main content

Middleware Overview

Zinc middleware uses the same shape as a route handler, so it composes directly with apps, groups, and individual routes.

func(*zinc.Context) error

Import first-party middleware from one package:

import "github.com/0mjs/zinc/middleware"

Start with a normal stack

Most APIs start with request identity, logging, panic recovery, CORS, body limits, and security headers.

app.Use(middleware.RequestID())
app.Use(middleware.RequestLogger())
app.Use(middleware.Recover())
app.Use(middleware.CORS("https://app.example.com"))
app.Use(middleware.BodyLimit(10 * middleware.MB))
app.Use(middleware.Secure())

Add auth, metrics, rate limiting, compression, and static files only where the application needs them.

Security

MiddlewareUse it for
CORSBrowser cross-origin policy and preflight responses
CSRFCookie-backed CSRF protection for browser-facing forms and fetch requests
SecureCommon browser security response headers
Header GuardsReject unsupported content types or route by request headers

Authentication and sessions

MiddlewareUse it for
JWTBearer token parsing, validation, and typed claims
Basic AuthSimple admin or internal route protection
Key AuthAPI keys from headers, query values, cookies, or custom extractors
Casbin AuthAuthorization through a Casbin-compatible enforcer
SessionSmall signed cookie-backed session values

Observability

MiddlewareUse it for
Request LoggerStructured request logs with status, timing, route, headers, and errors
Request IDGenerate or propagate request IDs through X-Request-ID
PrometheusDependency-free request counters and duration metrics
JaegerUber-Trace-Id propagation and span observation
PprofStandard library profiling routes behind Zinc middleware
Body DumpRequest and response body snapshots for debugging or auditing

Traffic control

MiddlewareUse it for
Rate LimiterToken-bucket limits by app, IP, or custom key
Body LimitReject oversized request bodies
Context TimeoutAttach per-request deadlines to the handler chain
RecoverConvert panics into Zinc's normal error flow
UtilityThrottle, Heartbeat, NoCache, Maybe, RealIP, and SetHeader

Transport and routing helpers

MiddlewareUse it for
GzipCompress responses for clients that accept gzip
DecompressDecode gzip request bodies before handlers read them
Method OverrideTunnel PUT, PATCH, or DELETE through POST
Trailing SlashAdd, remove, or redirect trailing slash variants
RewriteRewrite request paths before route dispatch
RedirectRedirect exact or wildcard paths
ProxyReverse proxy requests with net/http/httputil
StaticServe static files from middleware

Where middleware belongs

Use app-level middleware for behavior that should wrap every request.

app.Use(middleware.RequestID(), middleware.RequestLogger())

Use group middleware for a route family.

api := app.Group("/api")
api.Use(middleware.JWT(keyFunc))

Use route middleware when the behavior belongs to one endpoint.

app.Post("/exports", middleware.RateLimiter(), startExport)

See also