Middlewares
Middlewares are used to defined actions before and after each request. For example, if we want to authenticate the context before it gets into the context, we can define a middleware as this:
func AuthMiddleware(next golf.Handler) golf.Handler {
fn := func(ctx *golf.Context) {
if authenticate(ctx) {
next(ctx)
} else {
NotFoundHandler(ctx)
}
}
return fn
}
After the middleware is defined, we need to define a middleware chain. A middleware chain contains a sequence of middlewares. Middlewares in the middleware chain will be called as the defined sequence.
To apply a handler to a middleware chain and pass it to a route, we need to call the Final
method of the chain:
authChain := golf.NewChain(handler.AuthMiddleware)
App.Get("/admin/", authChain.Final(handler.AdminHandler))
App.Get("/admin/settings/", authChain.Final(handler.AdminSettingsHandler))
Updated less than a minute ago