Back to Blog

Context Package: Cancellation, Timeouts & Deadlines | Go Tutorial #28

Sandy LaneSandy Lane

Video: Context Package: Cancellation, Timeouts & Deadlines | Go Tutorial #28 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Context Package: Cancellation, Timeouts & Deadlines in Go

The Go context package provides powerful tools for managing cancellation signals, timeouts, deadlines, and request-scoped data in concurrent programs. It is essential for writing robust networked applications, allowing you to propagate cancellation signals and pass contextual information safely across API boundaries.

Code

package main

import (
  "context"
  "fmt"
  "time"
)

func main() {
  // Create a root context, usually context.Background() or context.TODO()
  ctx := context.Background()

  // Create a cancellable context derived from the root context
  ctx, cancel := context.WithCancel(ctx)

  // Start a goroutine that listens for cancellation
  go func(ctx context.Context) {
    select {
    case <-ctx.Done():
      fmt.Println("Goroutine: context cancelled:", ctx.Err())
      return
    }
  }(ctx)

  // Simulate some work
  time.Sleep(1 * time.Second)

  // Cancel the context manually
  cancel()

  // Wait a bit to observe cancellation effect
  time.Sleep(500 * time.Millisecond)

  // Example of timeout context
  ctxTimeout, cancelTimeout := context.WithTimeout(context.Background(), 2*time.Second)
  defer cancelTimeout()

  select {
  case <-time.After(3 * time.Second):
    fmt.Println("Operation completed")
  case <-ctxTimeout.Done():
    fmt.Println("Timeout reached:", ctxTimeout.Err())
  }

  // Using context.WithValue to pass request-scoped data
  type key string
  ctxWithValue := context.WithValue(context.Background(), key("userID"), 42)
  userID := ctxWithValue.Value(key("userID"))
  fmt.Println("User ID from context:", userID)
}

Key Points

  • context.Background() and context.TODO() provide root contexts for deriving others.
  • context.WithCancel() creates a context that can be cancelled manually, propagating cancellation to child contexts.
  • context.WithTimeout() and context.WithDeadline() automatically cancel the context after a set duration or deadline.
  • context.WithValue() safely passes request-scoped data using typed keys to avoid collisions.
  • Passing context explicitly in function parameters is a best practice to manage cancellation and deadlines consistently.