Sobes.tech
Junior

What is a context in Go? What is it used for, what types are there, and what patterns exist for working with it?

sobes.tech AI

Answer from AI

In Go, the context (package context) is a mechanism for passing cancellation signals, deadlines, and other values between goroutines.

Purpose:

  • Managing the lifetime of operations (e.g., canceling an HTTP request on timeout).
  • Passing cross-cutting data (e.g., request identifiers for logging).

Types of context:

  • context.Background() — the root, empty context.
  • context.TODO() — used when the context is not yet defined.
  • Contexts with cancellation (WithCancel), with timeout (WithTimeout), with deadline (WithDeadline), with values (WithValue).

Working patterns:

  • Pass the context as the first parameter to functions.
  • Do not store the context in structures, pass it explicitly.
  • Check for cancellation via <-ctx.Done().

Example:

ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
 defer cancel()

select {
case <-time.After(time.Second * 10):
    fmt.Println("operation finished")
case <-ctx.Done():
    fmt.Println("operation cancelled or timed out")
}