Extending echo.Context with user information


#1

Hi,

I created a middleware for echo v3 which validates a session cookie, looks up the userID from database and then returns next ( c ). Is there a way to “pass along” the userID (or other user related information) into the handler that handles the request? So I can access it from within the handler? Like “injecting” my own User struct into echo.Context?

Thanks


#2

Have you looked at Context#Set/Get api? For reference, you can look into this middleware https://github.com/labstack/echo/blob/master/middleware/jwt.go#L155. Another way is to extend context https://echo.labstack.com/guide/context.


#3

It looks like it is also possible to use context.Context if you want non-string keys.

func middleware(next echo.HandlerFunc) echo.HandlerFunc {
  return func(c echo.Context) error {
    request := c.Request()
    // get user somehow
    ctx := context.WithValue(request.Context(), userKey, user)
    c.SetRequest(request.WithContext(ctx))
    return next(c)
  }
}

Not sure if it is discouraged to set the request in your middleware, but it is nice to be able to use non-string keys for your context values.