Contexts with a deadline in Go
A context carries cancellation down a call tree, and every wait respects it.
func fetch(ctx context.Context, delay time.Duration) (string, error) {
select {
case <-time.After(delay):
return "fetched", nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func run() (string, error) {
ctx, cancel := context.WithTimeout(context.Background(),
20*time.Millisecond)
defer cancel()
return fetch(ctx, 200*time.Millisecond)
}
How it works
WithTimeoutcancels itself when the clock runs out.ctx.Done()is the channel to select on.ctx.Err()says whether it was canceled or timed out.
Keywords and builtins used here
casedefererrorfuncreturnselectstring
The run, in numbers
- Lines
- 15
- Characters to type
- 336
- Tokens
- 98
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 56 seconds.
Step 2 of 3 in Context, step 12 of 25 in Concurrency.