我正在使用 Golang 网络/上下文包将包装在上下文对象中的 ID 从一项服务传递到另一项服务。我能够成功传递上下文对象,但要实际检索特定键的值,context.Value(key) 总是返回 nil。我不确定为什么,但这是我到目前为止所做的:
if ctx != nil {
fmt.Println(ctx)
fmt.Println("Found UUID, forwarding it")
id, ok := ctx.Value(0).(string) // This always returns a nil and thus ok is set to false
if ok {
fmt.Println("id found %s", id)
req.headers.Set("ID", id)
}
}
ctx 是 context.Context 类型,在打印它时我得到:
context.Background.WithValue(0, "12345")
我有兴趣从上下文中获取值“12345”。从 Golang 网络/上下文文档 ( https://blog.golang.org/context ) 中,Value() 接受一个 interface{} 类型的键并返回一个 interface{} ,因此我将类型转换为 .(string)。有人可以帮忙吗?
最佳答案
您的上下文键不是 int
,它是未类型化常量 0
在 接口(interface)中传递给 Value 时将分配给的默认类型{}
。
c := context.Background()
v := context.WithValue(c, int32(0), 1234)
fmt.Println(v.Value(int64(0))) // prints <nil>
fmt.Println(v.Value(int32(0))) // print 1234
您还需要使用正确的类型设置和提取值。您需要定义一个始终用作键的类型。我经常定义辅助函数来提取上下文值并进行类型断言,在您的情况下,这也可以用于规范化键类型。
关于http - 从 Golang 中的网络/上下文中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37866616/