Http 从Golang中的网络/上下文获取值
我使用Golang net/context包将包装在上下文对象中的ID从一个服务传递到另一个服务。我能够成功地传递context对象,但要实际检索特定键的值,context.value(key)总是返回nil。我不知道为什么,但这是我迄今为止所做的:Http 从Golang中的网络/上下文获取值,http,go,header,httprequest,Http,Go,Header,Httprequest,我使用Golang net/context包将包装在上下文对象中的ID从一个服务传递到另一个服务。我能够成功地传递context对象,但要实际检索特定键的值,context.value(key)总是返回nil。我不知道为什么,但这是我迄今为止所做的: if ctx != nil { fmt.Println(ctx) fmt.Println("Found UUID, forwarding it") id, ok := ctx.Value(0).(s
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 net/context文档()中,Value()接受接口{}类型的键并返回接口{},因此I typecast是to.(string)。有人能帮忙吗?您的上下文键不是
int
,这是在接口{}
中将非类型常量0
传递给值时将分配给的默认类型
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
c:=context.Background()
v:=context.WithValue(c,int32(0),1234)
fmt.Println(v.Value(int64(0))//打印
fmt.Println(v.Value(int32(0))//print 1234
您还需要设置并提取具有正确类型的值。您需要定义一个始终用作键的类型。我经常定义helper函数来提取上下文值并执行类型断言,在您的例子中,这也可以用于规范化键类型 当您打印(“%+v”,ctx.Value(0))时会发生什么?我从ctx.Value(0)中得到。但是当我打印ctx时,我得到了全部信息:context.Background.WithValue(0,“12345”)键“0”的类型是什么?go将默认类型0为int,因此当您调用“Value(0)”时,它将调用Value(int(0))而不是Value(whatevertype0actuallyis(0))类型key int const(id key=iota)key设置为0,因为iota.iota只允许您高效地创建整数枚举,它没有类型,非常感谢@JimB。这正是问题所在。当我显式地将类型设置为int、int32或int64时,我能够检索它。看起来将其设置为iota并没有显式地将其类型转换为int。