LESSON · 1 OF 25

What a context carries

What a context carries

Once you have goroutines doing work, you need a way to tell them to stop. Maybe the user cancelled the request, maybe a deadline passed, or maybe the whole program is shutting down.

A context.Context is Go's standard tool for carrying that "stop now" signal across goroutine boundaries. You create one context, hand it to every goroutine and function involved in a piece of work, and when the work should end you cancel the context. Every goroutine holding it finds out and can bail out cleanly.

You will see context.Context all over the standard library and real Go code: HTTP handlers, database calls, and any function that might need to give up partway through. It is the shared channel for cancellation.

The rest of this topic builds it up one piece at a time: where a context comes from, how you cancel it, and how a goroutine notices.

Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute