Sobes.tech
Middle+

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

sobes.tech AI

Answer from AI

In Go, a context is a mechanism for passing request-scoped values, cancellation signals, and deadlines across API boundaries and between processes. It is used to manage the lifetime of operations, especially in network requests, request handling, and parallel computations.

Main features of context:

  • Canceling an operation
  • Setting a timeout or deadline
  • Passing values (e.g., request identifiers)

Example of usage:

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

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

Here, the operation will be interrupted after 5 seconds, even if it has not finished.