Home > Blockchain >  Cant add Contex Value with Chi from interface
Cant add Contex Value with Chi from interface

Time:03-10

i have data from interface, and i will add on context. from documentation is context.WithValue(r.Context(), key, val)

i try to add 1 key and value is work, but can't work if more than 1.

        result := map[string]interface{}{}
        encoded, _ := json.Marshal(data)
        json.Unmarshal(encoded, &result)
        fmt.Println("data claim \n", result)
        var ctx context.Context
        for key, val := range result {
            fmt.Printf("key %v value %v \n", key, val)
            ctx = context.WithValue(r.Context(), key, val)
        }
        fmt.Println("ctx middleware \n", ctx)

on result i have more than 1 data, but only 1 data is work.

CodePudding user response:

Could you please try this

        result := map[string]interface{}{}
        encoded, _ := json.Marshal(data)
        json.Unmarshal(encoded, &result)
        fmt.Println("data claim \n", result)
        ctx:=r.Context()
        for key, val := range result {
            fmt.Printf("key %v value %v \n", key, val)
            ctx = context.WithValue(ctx, key, val)
        }
        fmt.Println("ctx middleware \n", ctx)

Seems you are using r.Context() all the time but not the updated one.

CodePudding user response:

Since you're using the type string for the context key. This problem is already mentioned in the context document.

The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context

Here is the example for getting and setting key/value in context

package main

import (
    "context"
    "log"
)

// You need to define a type to prevent the collision
type key int

const fooKey key = 1
const barKey key = 2

func main() {

    ctx := context.Background()
    m := map[key]string{
        fooKey: "foo",
        barKey: "bar",
    }

    // Add to context
    for k, v := range m {
        ctx = context.WithValue(ctx, k, v)
    }

    // Get value from context
    for k := range m {
        v := ctx.Value(k).(string)
        log.Println("value is: ", v)
    }
}

  • Related