6 ms·
If your loop body is completely CPU-bound, then either adding a select statement, or a separate goroutine that awaits cancellation and closes the channel like c
by kinghajj 3y ago
If your loop body is completely CPU-bound, then either adding a select statement, or a separate goroutine that awaits cancellation and closes the channel like collinvandyck76 suggested, will work. But commonly the body will make other IO-bound calls to which the context gets passed, so you can just handle the error.
for item := range channel {
_, err := process(ctx, item)
if err != nil {
return err
}
}