Answer the question
In order to leave comments, you need to log in
How to get rid of the warning?
I'm trying to write a jwt middleware that will pass data from the token to the next function via context.
ctx := r.Context()
ctx = context.WithValue(ctx, "userID", tk.UserID)
ctx = context.WithValue(ctx, "token", tk.Token)
next.ServeHTTP(w, r.WithContext(ctx))
should not use basic type string as key in context.WithValue
Answer the question
In order to leave comments, you need to log in
You cannot use strings as keys, this will sooner or later lead to name conflicts.
When checking a key for a match, the context library compares the value and type of the key.
The key must not be a simple type, such as string, int, etc.
You need to create a separate type for the key.
This approach will allow you to have several values in the context with the same key, but of a different type.
Here is an example of how to do it right:
type contextKey uint
const (
UserIDContextKey contextKey = 1
)
...
ctx := r.Context()
ctx = context.WithValue(ctx, UserIDContextKey, tk.UserID)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question