duanning9110 2016-06-16 18:19
浏览 285
已采纳

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

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 ?

  • 写回答

1条回答 默认 最新

  • duanpanbo9476 2016-06-16 20:22
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?