在Golang中从net / context获取值 [英] Fetch value from net/context in Golang
问题描述
我使用Golang网络/上下文包来传递封装在上下文对象中的ID从一个服务到另一个服务。我能够成功传递上下文对象,但实际上会检索特定键的值,即上下文。值(键)总是返回nil。我不知道为什么,但这是我迄今为止所做的:
if ctx!= nil {
fmt.Println(ctx)
fmt.Println(找到UUID,转发它)
id,ok:= ctx.Value(0)。(string)//总是返回一个零,因此确定设置为假
如果确定{
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 ),价值()接受一个接口{}类型的键并返回一个接口{},因此我的类型转换为。(string)。任何人都可以帮忙吗? 你的上下文关键字不是 int
,这是默认类型,当传递给界面{}中的值时,无类型常量
0
将被分配给 c>。
c:= context.Background()
v:= context.WithValue(c ,int32(0),1234)
fmt.Println(v.Value(int64(0)))//打印< nil>
fmt.Println(v.Value(int32(0)))// print 1234
您需要使用正确的类型设置和提取值。您需要定义一个将始终用作键的单一类型。我经常定义辅助函数来提取上下文值并执行类型断言,在你的情况下,这也可以用来规范化键类型。
I am using Golang net/context package for passing on the ID's wrapped in a context object from one service to another. I am able to pass the context object successfully but to actually retrieve the value of a particular key, the context.Value(key) always returns a nil. I am not sure why, but this is what I have done so far:
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 is of the type context.Context and on printing it I get:
context.Background.WithValue(0, "12345")
I am interested in fetching the value "12345" from the context. From the Golang net/context documentation (https://blog.golang.org/context) , the Value() takes in a key of interface{} type and returns a interface{} and hence I typecast is to .(string). Could anyone help with this ?
Your context key is isn't an int
, which is the default type the untyped constant 0
will be assigned to when passed to Value in an interface{}
.
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
You need to set and extract the value with the correct type as well. You need to define a single type that you will always use as keys. I often times define helper functions to extract the context values and do the type assertion, which in your case could also serve to normalize the key type.
这篇关于在Golang中从net / context获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!