Writing Middleware
A middleware is typically a struct so that its dependencies can be injected by wire. For example, the following middleware protects internal routes with a bearer token:pkg/rockets/middleware.go
chttp.HandleMiddleware:
Registering Middleware
You may attach middleware to a single route using theMiddlewares field:
GlobalMiddlewares in pkg/app/handler.go:
pkg/app/handler.go
Built-in Middleware
Copper ships the middleware most apps need, already wired into new projects:chttp.SetRequestIDInCtxMiddleware()puts a unique request ID in the context. You may read it anywhere withchttp.GetRequestID(ctx).chttp.RequestLoggerMiddlewarelogs every request’s method, path, status code, and duration, and also records the built-inhttp_requests_totalandhttp_request_duration_secondsPrometheus metrics. See Metrics.csql.TxMiddlewarewraps mutating requests in a database transaction that commits or rolls back based on the response status. See Transactions.
Panic recovery is built into the handler itself, so there is no recovery middleware to register. A panicking handler is logged with its stack trace and the client receives a
500; you never need to add this yourself.