e := echo.New() e.GET("/hello/:name", func(c echo.Context) error { name := c.Param("name") return c.String(http.StatusOK, "Hello, "+name+"!") })
func authMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { token := c.Request().Header.Get("Authorization") if token != "secret-token" { return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized") } return next(c) } } e := echo.New() e.Use(authMiddleware) e.GET("/protected", func(c echo.Context) error { return c.String(http.StatusOK, "You are authorized to access this endpoint.") })This example shows how to use middleware functions to authenticate requests using the `Context` type. The `authMiddleware` function takes a `next` handler function, which is the next handler in the chain of middleware and handlers. It checks if the request has an "Authorization" header with the value "secret-token", and if it does not, it returns an HTTP error. If the request is authorized, the `next` handler is called, which returns a response indicating that the endpoint is protected. Package Library: `github.com.labstack.echo` is the package library.