Skip to content

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.

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.

These are the pieces most services add first.

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.