Package context defines the Context type for managing deadlines, cancellation, and request-scoped values
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context. The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context.
Returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline. Typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests.
Returns a derived context with a new Done channel. The returned context’s Done channel is closed when the cancel function is called or when the parent context’s Done channel is closed, whichever happens first.
func(parent Context, d time.Time) (Context, CancelFunc)
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 is semantically equivalent to parent.
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. Keys should be comparable and values should be safe for simultaneous use by multiple goroutines.
Tells an operation to abandon its work. Does not wait for the work to stop. May be called by multiple goroutines simultaneously. After the first call, subsequent calls do nothing.
Failing to call the CancelFunc leaks the child context and its children until the parent is canceled. Use defer to ensure the cancel function is called.
func gen(ctx context.Context) <-chan int { dst := make(chan int) n := 1 go func() { defer close(dst) for { select { case <-ctx.Done(): return // Exit when context is canceled case dst <- n: n++ } } }() return dst}func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() for n := range gen(ctx) { fmt.Println(n) if n == 5 { break } }}