Context Timeout And Cancellation Propagation
Bound blocking work with a context deadline, propagate cancellation through nested calls, and free resources on the deferred cleanup path.
Code
package main
import (
"context"
"errors"
"fmt"
"time"
)
func slowQuery(ctx context.Context, key string) (string, error) {
// 模拟一个可被取消的阻塞调用:select 监听 ctx.Done()
result := make(chan string, 1)
go func() {
time.Sleep(300 * time.Millisecond) // 模拟耗时
result <- "value-for-" + key
}()
select {
case value := <-result:
return value, nil
case <-ctx.Done():
// 上下文超时/取消时,err 一定非 nil
return "", fmt.Errorf("query %q: %w", key, ctx.Err())
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel() // 无论成败都释放定时器
value, err := slowQuery(ctx, "user-42")
if err != nil {
// errors.Is 识别根因:DeadlineExceeded 或 Canceled
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("deadline exceeded:", err)
return
}
fmt.Println("failed:", err)
return
}
fmt.Println("got:", value)
}Execution shape
Context Timeout And Cancellation Propagation is built around the functions slowQuery and main.
The Go idiom runs throughout — 1 if err != nil check, each handling the failure on the spot. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.
What to watch for
- Nothing to vet in a supply-chain review — the file pulls in no packages.
- No panic path here — failures come back as
errorvalues that each caller must handle.
Applying it
Entry signature: func slowQuery(ctx context.Context, key string) (string, error)
Running the file prints labeled results such as deadline exceeded:, failed:, got: — each operation’s effect is visible in the output.
The sequence slowQuery lives in main; running the file triggers it.
Statements that matter
return "", fmt.Errorf("query %q: %w", key, ctx.Err())
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("deadline exceeded:", err)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
Interactive Tools for This Topic
FAQ
- What is the error handling style?
- The Go way: `err` comes back from each call, and 1 checkpoint here test it before proceeding.
- What does Context Timeout And Cancellation Propagation print when run?
- No setup needed: run the file and look for labeled lines like `deadline exceeded:`, `failed:`, `got:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.