You use middleware in Echo by calling e.Use() with a function that wraps the next handler. This function executes before and after the handler, allowing you to modify requests or responses.
package main
import (
"github.com/labstack/echo/v4"
"net/http"
"time"
)
func main() {
e := echo.New()
// Middleware: Logs request start time
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
start := time.Now()
err := next(c)
c.Logger().Infof("%s %s %v", c.Request().Method, c.Request().RequestURI, time.Since(start))
return err
}
})
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.Start(":1323")
}