context
Index
- func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
- func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
- func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
- func Background() Context
- func TODO() Context
- func WithValue(parent Context, key, val any) Context
Functions
func WithCancel
1func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
WithCancel returns a copy of parent with a new Done channel. The returned context's Done channel is closed when the returned cancel function is called or when the parent context's Done channel is closed, whichever happens first.
Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.
This example demonstrates the use of a cancelable context to prevent a goroutine leak. By the end of the example function, the goroutine started by gen will return without leaking.
1gen := func(ctx context.Context) <-chan int {
2 dst := make(chan int)
3 n := 1
4 go func() {
5 for {
6 select {
7 case <-ctx.Done():
8 return
9 case dst <- n:
10 n++
11 }
12 }
13 }()
14 return dst
15}
16
17ctx, cancel := context.WithCancel(context.Background())
18defer cancel()
19
20for n := range gen(ctx) {
21 fmt.Println(n)
22 if n == 5 {
23 break
24 }
25}
Output
1 2 3 4 5
func WithDeadline
1func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
WithDeadline returns a copy of the parent context with the deadline adjusted to be no later than d. If the parent's deadline is already earlier than d, WithDeadline(parent, d) is semantically equivalent to parent. The returned context's Done channel is closed when the deadline expires, when the returned cancel function is called, or when the parent context's Done channel is closed, whichever happens first.
Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.
This example passes a context with an arbitrary deadline to tell a blocking function that it should abandon its work as soon as it gets to it.
1d := time.Now().Add(shortDuration)
2ctx, cancel := context.WithDeadline(context.Background(), d)
3
4defer cancel()
5
6select {
7case <-time.After(1 * time.Second):
8 fmt.Println("overslept")
9case <-ctx.Done():
10 fmt.Println(ctx.Err())
11}
Output
context deadline exceeded
func WithTimeout
1func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete:
func slowOperationWithTimeout(ctx context.Context) (Result, error) {
ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
defer cancel() // releases resources if slowOperation completes before timeout elapses
return slowOperation(ctx)
}
This example passes a context with a timeout to tell a blocking function that it should abandon its work after the timeout elapses.
1ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
2defer cancel()
3
4select {
5case <-time.After(1 * time.Second):
6 fmt.Println("overslept")
7case <-ctx.Done():
8 fmt.Println(ctx.Err())
9}
Output
context deadline exceeded
func Background
1func Background() Context
Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline. It is typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests.
func TODO
1func TODO() Context
TODO returns a non-nil, empty Context. Code should use context.TODO when it's unclear which Context to use or it is not yet available (because the surrounding function has not yet been extended to accept a Context parameter).
func WithValue
1func WithValue(parent Context, key, val any) Context
WithValue returns a copy of parent in which the value associated with key is val.
Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.
The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys. To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables’ static type should be a pointer or interface.
This example demonstrates how a value can be passed to the context and also how to retrieve it if it exists.
1type favContextKey string
2
3f := func(ctx context.Context, k favContextKey) {
4 if v := ctx.Value(k); v != nil {
5 fmt.Println("found value:", v)
6 return
7 }
8 fmt.Println("key not found:", k)
9}
10
11k := favContextKey("language")
12ctx := context.WithValue(context.Background(), k, "Go")
13
14f(ctx, k)
15f(ctx, favContextKey("color"))
Output
found value: Go key not found: color