golang context上下文,主要用来在多个goroutine之间传递上下文信息,实现取消信号、超时/截止时间、k-v信息传递等goroutine生命周期的控制。
使用语法和基本示例
- 请求级别的上下文传递,比如: 使用context传递 服务端 requestId。
func main() {
ctx := context.Background()
process(ctx)
ctx = context.WithValue(ctx, "traceId", "qcrao-2020")
process(ctx)
}
func process(ctx context.Context) {
traceId, ok := ctx.Value("traceId").(string)
if ok {
fmt.Printf("process over.trace_id=%s\n", traceId)
} else {
fmt.Printf("process over.no_trace_id\n")
}
}
- 定时取消: withTimeOut函数返回的context和cancelFun分开
func main() {
ctx, cancel := context.WithTimeout(context.Background, 1 * time.Second) // 1 or 5 time.Second
defer cancel()
ids := getResultFromWeb(ctx)
fmt.Prinln(ids)
}
func getResultFromWeb<