# Go Context 取消与超时实践 ## WithTimeout 示例 ```go package main import ( "context" "net/http" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com", nil) _, _ = http.DefaultClient.Do(req) } ``` ## 取消链路 ```go func worker(ctx context.Context) error { select { case <-time.After(500*time.Millisecond): return nil case <-ctx.Done(): return ctx.Err() } } ``` ## 规范 - 为外层创建的上下文负责取消 - 在阻塞点监听 `ctx.Done()` 并返回 `ctx.Err()` ## 总结 通过超时与取消信号传递,可提高服务的弹性与资源回收效率。

发表评论 取消回复