context.WithCancel, Context.Done, Context.Err
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
func Background() Context
func (c Context) Done() <-chan struct{}
func (c Context) Err() errorDerive a cancelable context, wait on Done after cancel, and read context.Canceled. Do not assume Err is set before Done is closed.
| Parameter | Description |
|---|---|
parent | The parent context, usually context.Background or a request context. Canceling the parent also cancels the child. |
Returns: WithCancel returns a derived Context and a CancelFunc. After Done is closed, Err returns context.Canceled for this construction. Before cancellation, Err returns nil.
- context.Canceled is the sentinel "context canceled". The example uses errors.Is to match it.
- A select on Background().Done() would block forever because that Done channel is nil. This page does not demonstrate a hang.
package main
import (
"context"
"errors"
"fmt"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
fmt.Println(ctx.Err() == nil)
cancel()
<-ctx.Done()
fmt.Println(ctx.Err())
fmt.Println(errors.Is(ctx.Err(), context.Canceled))
cancel()
fmt.Println(ctx.Err())
}Expected output
true
context canceled
true
context canceled