Sobes.tech
Senior

What is context in Go and what is it used for?

sobes.tech AI

Answer from AI

In Go, context is a package and a type used for passing request-scoped data, cancellation signals, and deadlines across API boundaries and between processes. It is essential for managing the lifecycle of operations, especially in network requests and long-running processes.

Main features of context:

  • Canceling operations (via context.CancelFunc) to stop work when necessary.
  • Passing deadlines (a time by which the operation should complete).
  • Passing request-specific values (e.g., request IDs) between functions.

Example usage:

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")
}

Thus, context helps control and coordinate the execution of asynchronous and long-running operations.

What is context in Go and what is it used for? — Golang - sobes.tech