Skip to content
On this page

Middleware

Think of middleware as a wrapper for the handlers we create. Sometimes, there are use cases where the same application logic needs to be applied to a multitude of resources within an application. A prime example of this type of logic is protecting the resources behind an authentication mechanism. An Echo middleware is defined as a function that takes the next function to call as a parameter and returns an Echo handler. By having the parameter be the next handler function to call, we are able to build a chain of handlers:

Middleware Request Processing Pipeline

Middleware functions are a great way to enrich requests with common functionality , that can be reusable across the application handler code. The use of middleware will significantly simplify your code and allow for greater reuse across your application. This middleware is executed after router processes the request and has full access toecho.ContextAPI. When defining a new route, we can optionally register middleware just for it.

How to write a custom middleware?

  • Middleware to collect request count, statuses and uptime.
  • Middleware to write custom Server header to the response.

Examples

go
// Create a new environment configuration
env := core.NewEnv()

 // Create a new Echo HTTP server
e := core.NewHTTPServer(&core.HTTPContextOptions{
  ContextOptions: &core.ContextOptions{
    ENV: env,
  },
})

e.GET("/", <Handler>, <Middleware...>)

Echo provides a lot of built-in middlewares, such as, BodyLimit, Logger, Gzip, Recover, BasicAuth, JWTAuth, Secure, CORS, and Static, which can be used out of the box.

We can use the default middleware Logger.

go
e.Use(middleware.Logger())

We can further modify each Middleware provided by Echo. Each middleware has the WithConfig method which can be used for customization. Let's, see how we can customize Logger middleware :

go
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
    Format: "method=${method}, uri=${uri}, status=${status}\n",
}))

We can also write custom middleware. Please find below a sample code of how to write custom middleware.

We can use the custom middleware same as regular middleware

go
e.Use(serverHeader)

Maintained by Passakon Puttasuwan & Dev Core Team.