I am building a web API with Echo Labstack framework. I have a middleware in my route to check for user authentication, but then I am having difficulty in passing the data to controller and could not find anything about this in Google and SO.
routes.go
func Routes(e *echo.Echo) {
e.(middlewareAuthorise)
user := e.Group("/user")
user.GET("/profile", controllers.UserProfile)
}
func middlewareAuthorise(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Do some authentication here with access token and get user ID
auth := controllers.Auth(c, 1)
if auth["status"] != 200 {
return c.JSON(401, map[string]any{"status": 401})
}
user_id := auth["user_id"]
// I want to pass user_id to my controllers
return next(c, user_id)
}
}
contollers.go
func UserProfile(c echo.Context) error {
// I want to get the user_id here from middleware
return c.JSON(200, map[string]any{
"user_id": user_id,
})
}
I have searched and tried several combinations for a whole day but couldn't find something that works. How do I pass the param from middleware to my controllers in the most efficient way possible?