Context With Value

Contoh code context WithValue dengan value string
Contoh code context WithValue dengan value map
Last updated

Last updated
package main
import (
"context"
"fmt"
)
func main() {
ctxA := context.Background()
// clild A
ctxB := context.WithValue(ctxA, "keyB", "member_01")
ctxC := context.WithValue(ctxA, "keyC", "member_02")
fmt.Println(ctxB.Value("keyB")) // member_01
fmt.Println(ctxB.Value("keyC")) // nil
fmt.Println(ctxC.Value("keyC")) // member_02
fmt.Println(ctxC.Value("keyB")) // nil
// child B
ctxD := context.WithValue(ctxB, "keyD", "member_03")
fmt.Println(ctxD.Value("keyB")) // member_01
fmt.Println(ctxD.Value("keyC")) // nil, karena bukan parent-nya
fmt.Println(ctxD.Value("keyD")) // member_03
}
member_01
<nil>
member_02
<nil>
member_01
<nil>
member_03package main
import(
"context"
"fmt"
)
func main() {
value := map[string]string{
"1": "one",
"2": "two",
}
background := context.Background()
child := context.WithValue(background, "value", value)
todo := context.TODO()
fmt.Println(background)
fmt.Println(child)
fmt.Println(child.Value("value"))
fmt.Println(todo)
}context.Background
context.Background.WithValue(type string, val <not Stringer>)
map[1:one 2:two]
context.TODO