Sobes.tech
Senior

Tell us about the types of contexts in Go: Background, WithTimeout, WithCancel, and others.

sobes.tech AI

Answer from AI

The Go package context is used for managing the lifetime of requests, canceling operations, and passing values between goroutines.

Main types of contexts:

  • context.Background() — a base, empty context, usually used as the root context in an application.
  • context.TODO() — a temporary context when it is not yet determined which one to use.
  • context.WithCancel(parent) — creates a new context that can be canceled manually by calling the cancel() function. Cancellation propagates to all child contexts.
  • context.WithTimeout(parent, duration) — creates a context that automatically cancels after a specified timeout.
  • context.WithDeadline(parent, time) — similar to WithTimeout, but with a specific date and time for expiration.
  • context.WithValue(parent, key, value) — creates a context with an attached value, which can be retrieved in child contexts.

Example of usage with timeout and cancellation:

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

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

Thus, contexts allow controlling the lifetime of operations, canceling them, and passing data between goroutines, which is especially important for network requests and long computations.

Tell us about the types of contexts in Go… - sobes.tech