---

title: Go Context 取消与超时实践

keywords:

  • Go
  • context
  • timeout
  • cancellation
  • deadline

description: 使用 Go 的 context 构建可取消与超时的请求链,覆盖 WithTimeout、WithCancel 与传递规范。

categories:

  • 文章资讯
  • 技术教程

---

Go Context 取消与超时实践

WithTimeout 示例

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)
}

取消链路

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()

总结

通过超时与取消信号传递,可提高服务的弹性与资源回收效率。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部