How to Check If a Context Is Done or Cancelled

Check if a Go context is done or cancelled by selecting on its Done channel or calling Err().

Check if a context is done or cancelled by selecting on its Done() channel or calling Err().

select {
case <-ctx.Done():
    // Context is done (cancelled or timed out)
    if ctx.Err() == context.Canceled {
        // Handle cancellation
    }
default:
    // Context is still active
}