github.com/code-reading/golang@v0.0.0-20220303082512-ba5bc0e589a3/coding/context/WithValue.go (about) 1 package main 2 3 import ( 4 "context" 5 "fmt" 6 ) 7 8 /* 9 需求: 在方法之间,goroutine之间,传递通用的token, trace_id 等通用参数 10 建议将ctx 放在函数的第一位, 并且 函数参数不要放到ctx中 11 也不要将ctx放到函数的结构体参数中 12 */ 13 14 // alias 15 type favContextKey string 16 17 func main() { 18 // 闭包 19 f := func(ctx context.Context, key favContextKey) { 20 // ctx.Value 取值 只返回一个值 没有返回两个 v,ok 21 if v := ctx.Value(key); v != nil { 22 fmt.Println("found the key: ", v) 23 return 24 } 25 fmt.Println("found not the key: ", key) 26 } 27 k := favContextKey("color") 28 // context.WithValue 只返回一个ctx 没有cancel, 不需要cancel 29 ctx := context.WithValue(context.Background(), k, "red") 30 f(ctx, k) 31 f(ctx, favContextKey("language")) 32 } 33 34 /* 35 found the key: red 36 found not the key: language 37 */