Sobes.tech
Middle+

Tell me about the context package in Go. What are contexts used for?

sobes.tech AI

Answer from AI

The context package in Go is used for passing request-scoped values, cancellation signals, and deadlines across API boundaries and between processes.

Main purposes of contexts:

  • Cancel operations: allows canceling related goroutines, for example, on timeout or request cancellation.
  • Pass deadlines: specify a time after which the operation should be aborted.
  • Pass values: transmit request-related data, such as identifiers or tokens.

Example 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 canceled or timeout expired")
}

Thus, contexts help control the execution of asynchronous operations and provide a convenient way to pass metadata between components.