ZhangZhihui's Blog  

IS THERE A WAY TO LIST KEYS IN CONTEXT.CONTEXT?

No there is no way to list all the keys of context.Context. Because that type is just an interface. So what does this mean?

In general a variable can hold a concrete type or an interface. A variable with an interface type does not have any concrete type informations on it. So it would makes no difference if the interface is empty (interface{}) or context.Context. Because they could be a lot of different types which are implementing that interface. The variable does not have a concrete type. It is just something abstract.

If you use reflection you could observe the fields and all the methods of the type which is set to that variable (with interface type). But the logic how the method Value(key interface{}) interface{} is implemented is not fixed. It does not have to be a map. You could also make an implementation with slices, database, an own type of an hash table, ...

So there is no general way to list all the values.

 

type ctxKey string

func main() {
    var key1 ctxKey = "k1"
    var key2 ctxKey = "k2"
    var key3 ctxKey = "k3"
    ctx := context.Background()
    ctx = context.WithValue(ctx, key1, "v1")
    ctx = context.WithValue(ctx, key2, "v2")
    ctx = context.WithValue(ctx, key3, "v3")
    fmt.Println(ctx)
    fmt.Printf("%v\n", ctx)

    for _, key := range [3]ctxKey{"k1", "k2", "k3"} {
        fmt.Printf("key: %v, value: %v\n", key, ctx.Value(key))
    }
}

 

zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
context.Background.WithValue(type main.ctxKey, val v1).WithValue(type main.ctxKey, val v2).WithValue(type main.ctxKey, val v3)
context.Background.WithValue(type main.ctxKey, val v1).WithValue(type main.ctxKey, val v2).WithValue(type main.ctxKey, val v3)
key: k1, value: v1
key: k2, value: v2
key: k3, value: v3

 

posted on 2024-02-25 13:39  ZhangZhihuiAAA  阅读(7)  评论(0编辑  收藏  举报