E
E
Eugene2020-02-28 13:40:08
go
Eugene, 2020-02-28 13:40:08

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))


But such a code is underlined in yellow and a message is displayed. What am I doing wrong?

should not use basic type string as key in context.WithValue


5e58edf95d43e543505280.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2020-02-28
@you_are_enot

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 question

Ask a Question

731 491 924 answers to any question