psb*_*its 1 header http httprequest go
我正在使用Golang net / context包将包装在上下文对象中的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)
}
}
Run Code Online (Sandbox Code Playgroud)
ctx是context.Context类型,在打印时得到:
context.Background.WithValue(0, "12345")
Run Code Online (Sandbox Code Playgroud)
我有兴趣从上下文中获取值“ 12345”。从Golang net / context文档(https://blog.golang.org/context)中,Value()接受interface {}类型的键并返回interface {},因此我将类型转换为。(string) 。有人可以帮忙吗?
您的上下文关键字不是int,这是默认类型0,当传递给中的Value时,未类型化常量将被分配给该类型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
Run Code Online (Sandbox Code Playgroud)
您还需要设置和提取具有正确类型的值。您需要定义一个始终用作键的单一类型。我经常定义辅助函数来提取上下文值并进行类型断言,在您的情况下,这也可以用来规范键类型。