实现说明
带截止时间的上下文取消的核心是函数 fetch、main。
失败在这里是值:1 处检查 err 并当场决定,而不是让它向上冒。defer 把清理钉在函数边界上,而不是散落在函数体里。
使用要点
- 没有安装步骤:用到的 API 全部随平台提供。
error在返回元组里,失败意味着什么由每个调用方决定。- 演示输出是带标签的(
deadline exceeded),每个操作都会留下自己的一行标注。 - 执行文件,
main会按顺序走完fetch。
常见问题
调用方该如何处理失败?
Go 的惯用法:err 随调用返回,这里有 1 个检查点先测它再继续。
运行「带截止时间的上下文取消」会打印什么?
运行文件本身,deadline exceeded 这些前缀各对应一段演示逻辑。
主签名形如 func fetch(ctx context.Context, url string) (string, error)
核心语句
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)
代码示例
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)
}