Reputation: 117
How to pass a parameter to middleware in Echo? There is an example of what I want to achieve.
func (h *handlers) Check(pm string, next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if pm == "test" {
return next(c)
}
return echo.NewHTTPError(http.StatusUnauthorized, "")
}
}
And I want to set the middleware like this:
route.Use(middleware.Check("test input"))
Upvotes: 4
Views: 7225
Reputation: 804
You can use a closure to give your parameter to the middleware, like this:
func (h *handlers) Check(adminName string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if c.QueryParam("username") == adminName {
return next(c)
}
return echo.NewHTTPError(http.StatusUnauthorized, "")
}
}
}
Here the middleware checks whether the query parameter username
matches the middleware parameter adminName
. With this example, anyone can get admin status if they know the right username, so no security. You may want to use the BasicAuth or JWT middleware instead, they are already available for echo
. Have a look at echo/middleware/basic_auth.go
for a better example.
And you can set the middleware as in your question:
route.Use(middleware.Check("admin"))
Upvotes: 11