首页 > 解决方案 > 进行批量调用时http请求中的Golang上下文

问题描述

我正在寻找了解使用带有上下文超时的 go 标准库进行 http 调用时我应该期望的行为。

我明白,如果我这样做:

ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080", nil)

该特定请求将在 200 毫秒内完成。这很好用,我明白了。

我的疑问是,如果我这样做会发生什么:

ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
for loop with a range from 1 to 20 {
  req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080", nil)
}

因此,在后一个示例中,我正在使用该上下文执行一堆请求。所有请求会分别超时 200 毫秒,还是会在我开始测距后 200 毫秒后开始失败?

笔记:

FATHER_CONTEXT, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)

defer cancel()
for loop with a range from 1 to 20 {
  ctx, cancel := context.WithTimeout(FATHER_CONTEXT, 200*time.Millisecond)
  req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080", nil)
} 

标签: gorangetimeout

解决方案


来自上下文文档

WithCancel、WithDeadline 和 WithTimeout 函数采用 Context(父)并返回派生的 Context(子)和 CancelFunc。调用 CancelFunc 会取消子项及其子项,删除父项对子项的引用,并停止任何关联的计时器

因此上下文由孩子及其孩子共享。所有请求将在 200 毫秒后超时。


推荐阅读