Sobes.tech
Junior — Middle

How to determine if the execution of the current context was interrupted or canceled?

sobes.tech AI

Answer from AI

In Go, to determine whether the current context has been canceled or aborted, the Done() method of the context.Context object is used. This method returns a channel that is closed when the context is canceled. Typically, the check is done as follows:

select {
case <-ctx.Done():
    // Context canceled or timeout exceeded
    err := ctx.Err() // context.Canceled or context.DeadlineExceeded
    // Handle cancellation
default:
    // Continue work
}

Thus, if the ctx.Done() channel is closed, it means the execution should be stopped.

How to determine if the execution of the current… - sobes.tech