Documentation
¶
Overview ¶
Middleware that returns an error instead of writing a response.
Middleware doing real work - a plan lookup, a database call - reads better when it can return an error instead of hand-writing a response. errors.FuncMiddleware from rest/errors converts a func(iris.Context) error into a normal iris.Handler:
- a nil return calls ctx.Next() and the chain continues;
- a non-nil return goes through the central error pipeline (mapping, logging, JSON rendering) and the request stops there.
The error's code name picks the status and the JSON "code": errors.Unauthenticated renders 401 UNAUTHENTICATED, errors.PermissionDenied 403 PERMISSION_DENIED, errors.InvalidArgument 400 INVALID_ARGUMENT. An unrecognized error becomes 500 INTERNAL and its text is logged rather than returned. errors.FuncHandler is the same conversion for a terminal handler (no Next on success), and errors.FuncHandlers converts a whole slice.
Authentication is NOT the thing to hand-write here: middleware/apikey already compares the presented key against the configured ones in constant time and renders the same 401 envelope, so it runs first and this example's own middleware is left with the question it alone can answer, which principal may read the data.
Learn: turn a func(iris.Context) error into middleware or a handler with errors.FuncMiddleware and errors.FuncHandler, and let the error code pick the status. Before: ../conditional
Run:
go run main.go
Try:
curl -i http://localhost:8080/data # 401 UNAUTHENTICATED, no key curl -i -H "X-API-Key: nope" http://localhost:8080/data # 401 UNAUTHENTICATED, unknown key curl -i -H "X-API-Key: trial-key" http://localhost:8080/data # 403 PERMISSION_DENIED curl -i -H "X-API-Key: demo-key" http://localhost:8080/data # 200 curl -i -H "X-API-Key: demo-key" http://localhost:8080/failing # 500 INTERNAL
Next: ../cors