How to pass a value to middleware?
marcelloh opened this issue · 2 comments
marcelloh commented
Normally I would use middleware like this:
router.Use(middleware.MyMiddleware).GET("/demo", myDemoHandler)
But let's say, I want to check in the middleware if the user has permissions to use the handler.
Something like this:
router.Use(middleware.Permissions("RW")).POST("/demo", myDemoHandler)
How can I achieve something like this?
vmihailenco commented
You can pass the user or perms in context.Context
, for example - https://github.com/uptrace/uptrace/blob/master/pkg/tracing/grafana_handler.go#L27-L50
marcelloh commented
So before calling the middleware.Permissions, I have to set the wanted "RW" inside a context that I can read back inside that middleware?
I want to achieve something like:
router.Use(middleware.Permissions("R")).GET("/demo", myDemoHandler)
router.Use(middleware.Permissions("R")).POST("/demo", myDemoHandler)
router.Use(middleware.Permissions("RW")).GET("/secret", mySecretHandler)
In your example, I see that In the middleware, to context is created and passed to the underlying handler method.
(In my desired solution, it needs to happen before that.)