Create a Middleware

Middleware is a function that receives a Handle and returns a Handle. Let’s take ServerHeader as an example, it writes Server header and then invokes the next middleware or handler.

  1. func ServerHeader(srv string) clevergo.MiddlewareFunc {
  2. return func(next clevergo.Handle) clevergo.Handle {
  3. return func(ctx *clevergo.Context) error {
  4. // writes server header.
  5. ctx.Response.Header().Set("Server", srv)
  6. // invokes the next middleware or handler.
  7. return next(ctx)
  8. }
  9. }
  10. }

Global Middleware

  1. router.Use(
  2. clevergo.Recovery(true), // built-in recovery middleware.
  3. ServerHeader("CleverGo"),
  4. )

Route Group Middleware

See Route Group.

Route Middleware

See Route Middleware.

Third-party Middleware

WrapHH is an adapter that converts func(http.Handler) http.Handler to a middleware, you can use most of the third-party middleware in CleverGo without a struggle.

  1. router.Use(
  2. // https://github.com/nytimes/gziphandler
  3. clevergo.WrapHH(gziphandler.GzipHandler),
  4. )