Middleware
Middleware
Choose and compose Zinc's first-party middleware.
Zinc ships 29 middleware in one package, github.com/0mjs/zinc/middleware. Each is an ordinary func(*zinc.Context) error, so you can attach it to the whole app, a group, or a single route. Standard net/http middleware works too, through app.UseHTTP.
A good default stack
Section titled “A good default stack”Most JSON APIs start here. Order matters: each entry wraps everything after it.
app.Use( middleware.RequestID(), // 1. tag the request first, so everything can log the ID middleware.RequestLogger(), // 2. log every request, including failures below middleware.Recover(), // 3. turn panics into 500s that the logger records middleware.Secure(), // 4. browser security headers)Add CORS when browsers on other origins call the API, Context Timeout to bound slow requests, and an auth middleware on the groups that need it.
Start with the request path
Section titled “Start with the request path”These are the pieces most services add first.
Identity and access
Section titled “Identity and access”Delivery and observability
Section titled “Delivery and observability”Request shaping
Section titled “Request shaping”Put middleware where it belongs
Section titled “Put middleware where it belongs”Use app middleware for 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 for one endpoint:
app.Post("/exports", middleware.RateLimiter(), startExport)Read Groups and Middleware for execution order
and c.Next(), or Errors for returned middleware errors.