【发布时间】:2021-11-05 08:23:11
【问题描述】:
我正在寻找了解在使用带有上下文超时的 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)
}
【问题讨论】:
-
上下文是共享的。当它过期时,它对所有请求都过期。创建上下文 200 毫秒后,所有请求都将失败。
-
谢谢先生!如果我的新上下文是从以前的上下文中创建的,会发生什么?父上下文也会重置它的超时吗?
-
我添加了一个例子来说明我的意思
-
这是文档中的解释。 “子上下文”在父上下文取消时取消。这就是 for 的上下文。