How do I add middleware with Echo in Go?

In Go, you can add middleware to your Echo web application to handle additional logic before or after your route handlers. Middleware functions can be used for logging, authentication, error handling, and more.

Example of Adding Middleware in Echo


package main

import (
    "net/http"
    "github.com/labstack/echo/v4"
)

// Middleware function
func exampleMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
    return func(c echo.Context) error {
        // Do something before the handler
        return next(c) // call the next handler
    }
}

func main() {
    e := echo.New()

    // Register the middleware
    e.Use(exampleMiddleware)

    e.GET("/", func(c echo.Context) error {
        return c.String(http.StatusOK, "Hello, World!")
    })

    e.Start(":8080")
}
    

go middleware echo web application