I'm building a Rest API with Gin and I want to store currently logged-in user's roles somewhere I can reach within the application for each request to check that user's permission for the requested operation.
When a request comes, the application gets JWT from Gin Context, and with that token, the application extracts the ID and roles of that user. I want to put those roles somewhere I can reach from other parts of the application such as permission check service.
How can I achieve that?
Comment From: nesselchen
You've probably figured this out by now but you can store the ID in the key-value store inside the gin.Context. Just store it using ctx.Set
and retrieve it with ctx.Get
. gin even has some custom getters (GetInt, GetString) that return the specified type instead of interface{}.
It is then common practice to pass the extracted value to a function or method that handles the specific use case. So don't pass your gin.Context around your whole request chain, instead, get the user ID inside a middleware, extract it from the gin.Context inside your handler and then pass the ID to a service.