Context包
image.png
Context接口
image.png
1.1 emptyContext
type emptyCtx int
Background()
Background返回一个非空的Context。 它永远不会被取消,没有价值,也没有最后期限。 它通常由主要功能,初始化和测试使用,并且用作传入请求的顶级上下文。
image.png
1.2 cancelContext
image.png
image.png
1.3 timerCtx
image.png
timer 来触发 cancelCtx, cancelFunc := context.withCancel(ctx) 的取消函数,实现定时功能
image.png
当ctx2取消时,只会取消ctx2
当ctx1取消时,会去取消ctx1 包括他的children集中存储的所有context
1.4 valueCtx
image.png
给context添加一个键值对信息,就可以通过context来传递数据
例:当父context ctxA存储的key 和子context ctxC存储的key相同时,获取会覆盖父节点value
image.png
因为Value()函数先对比key的类型是否相同,如果都是基本类型,且值相同,会返回当前ctx的值,
使用时,应该包装key,就会查找父ctx的值
image.png
图片截自:B站 eggo实验室