英文:
Go: How to use context value in a variable?
问题
我正在使用上下文将用户负载(特别是用户ID)附加到我的Go REST应用程序的中间件中。
// 中间件
// 将负载附加到请求上下文
claimsWithPayload, _ := token.Claims.(*handlers.Claims)
ctx := context.WithValue(r.Context(), "userid", claimsWithPayload.Id)
req := r.WithContext(ctx)
h := http.HandlerFunc(handler)
h.ServeHTTP(w, req)
然后在HTTP处理程序中,我需要提取该用户ID作为string/integer
,但是context().Value()
返回一个interface{}
。
// 处理程序
a := r.Context().Value("userid") // 这返回一个interface{}
response := []byte("您的用户ID是" + a) // 如何将其用作字符串/整数??
w.Write(response)
请注意,上述代码片段中的注释已经被我翻译成了中文。
英文:
I am using context to attach user payload(userId specifically) in a middleware for my go rest application
// middleware
// attaching payload to the request context
claimsWithPayload, _ := token.Claims.(*handlers.Claims)
ctx := context.WithValue(r.Context(), "userid", claimsWithPayload.Id)
req := r.WithContext(ctx)
h := http.HandlerFunc(handler)
h.ServeHTTP(w, req)
And later in a http handler, I need to extract that userid as string/integer
but context().Value() returns an interface{}
// handler
a := r.Context().Value("userid") // THIS returns an interface{}
response := []byte("Your user ID is" + a) // 👈 how do I use it as a string/integer??
w.Write(response)
</details>
# 答案1
**得分**: 7
你可以使用类型断言将上下文值转换为其底层类型:
```go
a := r.Context().Value("userid").(string)
如果中间件存储的值不是字符串,或者其他内容将上下文键设置为非字符串值,这将引发恐慌。为了防止这种情况发生,你不应该使用内置类型作为上下文键,而是定义自己的类型并使用它:
type contextKey string
const userIDKey contextKey = "userid"
...
ctx := context.WithValue(r.Context(), userIDKey, claimsWithPayload.Id)
...
a := r.Context().Value(userIDKey).(string)
由于contextKey
和userIDKey
是未导出的,只有你的包才能从上下文中读取或写入该值。
英文:
You can use a type assertion to get the context value as its underlying type:
a := r.Context().Value("userid").(string)
This will panic if the value stored by the middleware is not a string, or if something else sets the context key to something which is not a string. To guard against this you should never use builtin types as context keys, instead define your own type and use that:
type contextKey string
const userIDKey contextKey = "userid"
...
ctx := context.WithValue(r.Context(), userIDKey, claimsWithPayload.Id)
...
a := r.Context().Value(userIDKey).(string)
Because contextKey
and userIDKey
are unexported, only your package can read or write this value from or to the context.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论