Context Cancellation With Deadline
Derive a context with a deadline so downstream work is cancelled when the caller gives up, and propagate the reason through context errors.
Code
package main
import (
"context"
"errors"
"fmt"
"time"
)
func fetch(ctx context.Context, url string) (string, error) {
select {
case <-time.After(200 * time.Millisecond):
return "payload from " + url, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
result, err := fetch(ctx, "https://api.example.com/data")
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("deadline exceeded")
return
}
panic(err)
}
fmt.Println(result)
}How it works
Count the functions fetch and main as the entire surface area of Context Cancellation With Deadline.
Failures are values here: 1 site check err and decide instead of letting one propagate. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
What to watch for
- Nothing to install: every API here comes with the runtime itself.
erroris part of the return tuple, so every caller decides what failure means.
Putting it to use
Entry signature: func fetch(ctx context.Context, url string) (string, error)
Output lines are prefixed (deadline exceeded), so each printed line stays traceable to the step behind it.
There are 1 call inside main — fetch — executed top to bottom.
Core lines under the microscope
func fetch(ctx context.Context, url string) (string, error) {
select {
case <-time.After(200 * time.Millisecond):
return "payload from " + url, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("deadline exceeded")
return
}
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
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.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
- How should callers handle failures?
- The Go way: `err` comes back from each call, and 1 checkpoint here test it before proceeding.
- What does Context Cancellation With Deadline print when run?
- No setup needed: run the file and look for labeled lines like `deadline exceeded` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.