25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Using Context for Cancellation and Timeouts in Go
Code Snippet

Using Context for Cancellation and Timeouts in Go

go

The context package is Go’s standard way to handle cancellation and timeouts across goroutines and API boundaries. A context carries deadlines, cancellation signals, and request-scoped values through your program. context.WithTimeout() creates a child context that automatically cancels after a specified duration, while context.WithCancel() allows manual cancellation.

The key pattern is to check ctx.Done() in your goroutines using select statements. When a context is cancelled, its Done() channel closes, signaling all listening goroutines to stop. This propagates cancellation signals efficiently throughout your concurrent code without explicit shutdown mechanisms.

Context is essential for building robust concurrent systems because it allows you to set deadlines on entire operations, cancel long-running work, and prevent goroutine leaks. Always pass context as the first parameter to functions and respect its cancellation signal.

Further Reading: