What Is context.Context in Go and Why It Matters

context.Context manages deadlines, cancellation, and request values across Go goroutines to prevent resource leaks.

context.Context is a Go interface that carries deadlines, cancellation signals, and request-scoped values across API boundaries and between goroutines. It enables you to stop long-running operations or propagate metadata without passing explicit arguments through every function call.

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

// Use ctx in your function calls
result, err := doWork(ctx)
if err == context.DeadlineExceeded {
    // Handle timeout
}