Context
context使用
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
func WithValue(parent Context, key, val interface{}) Context
- context提供4种实现

传递共享数据
package main
import (
"context"
"fmt"
)
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")
}
}
定时取消
package main
import (
"context"
"testing"
)
func TestTimeoutContext(t *testing.T) {
ctx, can := context.WithTimeout(context.Background(), 1*time.Second)
defer can()
go func() {
for {
select {
case <-ctx.Done():
t.Log("done")
return
default:
t.Log("not done")
}
}
}()
}