Sobes.tech
Senior

Milleks kasutatakse konteksti? Kuidas seda praktikas kasutasite?

sobes.tech AI

Vastus AI-lt

In Go, context is used to pass cancellation signals, timeouts, and other values between goroutines, especially when working with requests, timeouts, and operation cancellations.

Practical application:

  • Cancel long-running operations when closing an HTTP request.
  • Transmit a timeout so that an operation does not run longer than the specified time.
  • Pass metadata (e.g., request identifiers) through the call chain.

Example of usage:

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

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

Here, the operation will be interrupted after 2 seconds, even if it is scheduled for 5.