Context Basics in Go
What context.Context is, how contexts form a tree from Background, and how to stop work early with WithCancel.
context.Context is how Go code passes a stop signal, a deadline and a few request-scoped values through all the functions doing one piece of work. This section explains the interface and the most basic way to use it: cancelling by hand.
What context.Context Is
Contexts form a tree that starts at context.Background(). Cancelling a parent cancels every child. Functions take the context as their first parameter, named ctx.
func FetchUser(ctx context.Context, id int) (*User, error)
Cancelling with WithCancel
ctx, cancel := context.WithCancel(parent) returns a function that closes ctx.Done().
Always call cancel:
go vet warns when a cancel function is discarded. Write defer cancel() right after creating the context.
Summary
Pass ctx first, derive children for new limits, and make long-running code watch ctx.Done().
What context.Context Is in Go
What the context package is for, the four methods of context.Context, where Background and TODO fit, and why ctx is always the first parameter.
Cancelling Work with context.WithCancel
Stop goroutines early with context.WithCancel, why you must always call cancel, and how to make your own functions respect ctx.Done().