http - 从 Golang 中的网络/上下文中获取值

标签 http go header httprequest

我正在使用 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/

相关文章:

if-statement - if 语句中的结构初始化

c# - 如何使用 HttpWebRequest 将 XML 流发布到 wcf http rest 服务

android - 是否可以从网络服务器上的目录加载图像?

http - 转到net/http Transport Accept-Encoding : gzip not prompting encoded response

linux - Apache2虚拟主机文件

当我编译新代码时,Go 的 JWT token 过期

windows - 在 Go 中读取 XML 文件

mysql - 警告 : mysql_fetch_array() expects parameter 1 && Warning: Cannot modify header information - headers already sent

c++ - 在 Xcode 4 中包含 C/C++ header

html - 如何使用 css 让我的 iframe 卡在固定的页眉和页脚之间?