Sobes.tech
Senior

What is context in Go and how is it used?

sobes.tech AI

Answer from AI

In Go, the context package is used to pass cancellation signals, deadlines, and other values between goroutines, especially in distributed and multithreaded applications.

Main features of context:

  • Cancellation — allows interrupting the execution of a goroutine.
  • Timeouts and deadlines — limit the execution time.
  • Passing values — allows transmitting data related to the request.

A typical usage scenario is passing context to functions that perform long-running operations, so their completion can be controlled.

Example:

func doWork(ctx context.Context) {
    select {
    case <-time.After(5 * time.Second):
        fmt.Println("Work done")
    case <-ctx.Done():
        fmt.Println("Work cancelled")
    }
}

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

    doWork(ctx)
}

Here, the work will be interrupted after 2 seconds, even if 5 seconds have not yet passed.