4

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"))
Clément
  • 804
  • 6
  • 16
Hossein
  • 115
  • 1
  • 11

1 Answers1

11

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"))
Clément
  • 804
  • 6
  • 16
  • 1
    I've used the parameter in the same way as in your question, but obvious there would not be much value in using such a middleware. – Clément Oct 03 '19 at 07:24
  • I want this middleware for checking user access level by passing the needed role as a parameter to the middleware, what's your approach to doing that? @clément – Hossein Oct 03 '19 at 09:21
  • My answer applies if you want to set a parameter to the middleware. I think what you're trying to do is getting a parameter from the query instead, which you can get from the context. You can combine both, I've edited my answer to illustrate. – Clément Oct 03 '19 at 09:43
  • No, I want to get a parameter from middleware function. I want to have a one middleware for all different ACL check, something like adminRoute.Use(Check(admin)) and userRoute.Use(Check(user)). @clément – Hossein Oct 03 '19 at 09:46
  • Right, I see. Well, the code in the answer works for that. – Clément Oct 03 '19 at 09:51