Context Cancellation Propagation
Propagate cancellation and deadlines through a call tree using Go context, so abandoned work stops promptly.
Code
package request
import (
"context"
"errors"
"time"
)
var ErrTimeout = errors.New("request timed out")
type Result struct {
Value int
Err error
}
func fetch(ctx context.Context, work func(context.Context) (int, error)) (int, error) {
resultCh := make(chan Result, 1)
go func() {
value, err := work(ctx)
resultCh <- Result{Value: value, Err: err}
}()
select {
case <-ctx.Done():
return 0, ErrTimeout
case result := <-resultCh:
return result.Value, result.Err
}
}
func WithDeadline(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
return context.WithTimeout(parent, timeout)
}How the snippet works
Under the hood: the functions fetch and WithDeadline.
A goroutine does the work; a channel carries the result back, so the two contexts never share memory directly.
Watch out for
- Wholly standard-library — paste it in and it executes.
Applying it
The one callable in this file is func WithDeadline(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc)
Import WithDeadline from the file and call it — the rest of the code is implementation detail.
Statements that matter most here
func WithDeadline(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
return context.WithTimeout(parent, timeout)
}
resultCh <- Result{Value: value, Err: err}
var ErrTimeout = errors.New("request timed out")
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. Every import resolves inside the standard library — `context`, `errors`, `time`. The file defines `fetch`, `WithDeadline` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.