context上下文(一)
创建一个基础的context
使用BackGround函数,BackGround函数原型如下:func Background() Context { return backgroundCtx{} }
作用:
Background
函数用于创建一个空的context.Context
对象。
context.Background()
函数用于获取一个空的context.Context
对象。这个对象没有设置任何的截止时间(deadline),也没有取消通道(cancelation signal),并且不包含任何键值对(values)。它通常被用作根context
,即在开始一个新的 goroutine 或启动一个新的操作时,如果没有更具体的context
可用,就可以使用context.Background()
获取的context
。ctx := context.Background() //创建一个基础context
ctx的类型为:实现context.Context接口的类型
type Context interface { Deadline() (deadline time.Time, ok bool) Done() <-chan struct{} Err() error Value(key any) any }
使用WithValue向ctx添加键值对
//func WithValue(parent Context, key, val any) Context ctx = context.WithValue(ctx, "userID", "123456")
定义一个函数,接收context参数
funcWithCtx := func(ctx context.Context) { //从context中检索值 if value := ctx.Value("userID"); value != nil { fmt.Println("User ID from context", value) } else { fmt.Printf("No User ID from context") } }
因为Context接口类型中有Value(key any) any
通过传入的context对象中检索名为“userID”的值通过【通过键查找值】
完整代码
package main import ( "context" "fmt" ) func main() { //func Background() Context ctx := context.Background() //创建一个基础context ctx = context.WithValue(ctx, "userID", "123456") //使用WithValue向context中添加键值对 //定义一个函数,接受一个context参数 funcWithCtx := func(ctx context.Context) { //从context中检索值 if value := ctx.Value("userID"); value != nil { fmt.Println("User ID from context", value) } else { fmt.Printf("No User ID from context") } } funcWithCtx(ctx) //调用函数,传递context }