6

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 ?

8
  • What happens when you print ("%+v", ctx.Value(0)) Commented Jun 16, 2016 at 20:11
  • I get <nil> for ctx.Value(0). But when I print ctx I get the whole thing: context.Background.WithValue(0, "12345") Commented Jun 16, 2016 at 20:16
  • What is the type of the key '0'? go will default the type of 0 to int so When you call "Value(0)" it will call Value(int(0)) instead of Value(whatevertype0actuallyis(0)) Commented Jun 16, 2016 at 20:21
  • type key int const ( id key = iota ) key is set to 0 because of iota. Commented Jun 16, 2016 at 20:31
  • 1
    iota just lets you create integer enums efficiently it doesn't have a type golang.org/ref/spec#Iota Commented Jun 16, 2016 at 21:01

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much @JimB. That is exactly the issue. When I explicitly set the type to int or int32 or int64 , I am able to retrieve it. Looks like setting it to iota doesn't explicitly typecast it to int.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.