Sobes.tech
Middle

What is a context in Go? How is it used? How does cancellation through context work?

sobes.tech AI

Answer from AI

In Go, context is a package used for passing cancellation signals, deadlines, and other values between goroutines, especially when working with requests and external operations.

Main features of context:

  • Cancellation: allows canceling an operation if it is no longer needed or has exceeded the timeout.
  • Deadline: sets a time after which the operation is automatically canceled.
  • Passing values: can pass data, such as request identifiers.

How it is used:

A base context is created, usually context.Background() or context.TODO(). Then, derived contexts with a timeout, deadline, or cancellation capability are created.

Example with cancellation:

import (
    "context"
    "fmt"
    "time"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())

    go func() {
        time.Sleep(2 * time.Second)
        cancel() // Cancel the context after 2 seconds
    }()

    select {
    case <-time.After(5 * time.Second):
        fmt.Println("Operation completed")
    case <-ctx.Done():
        fmt.Println("Operation canceled:", ctx.Err())
    }
}

How cancellation works through context:

  • When the cancel() function is called or the deadline is reached, the ctx.Done() channel is closed.
  • All goroutines listening to this channel receive a cancellation signal and can terminate properly.

Thus, context helps manage the lifetime of operations and coordinate cancellation between goroutines.