重定向的上下文超时而不是使用客户端超时?

时间:2017-05-21 15:22:16

标签: redirect go timeout httprequest

我使用显式http.Client.Timeout

从客户端执行HTTP请求
client := http.Client{
    Timeout: timeout, // 5 seconds
}

httpResponse, err := client.Do(httpRequest)

但是这个客户端会执行一系列重定向(我不知道有多少重定向)。

根据我的理解,每次重定向都会重启超时,因此5秒的超时时间为five-seconds * num-of-redirects

是否可以而不是在context.Context 内传递超时?

ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
// do I need cancel?
httpRequest.WithContext(ctx)
httpResponse, err := client.Do(httpRequest)

这会在同一超时中包含请求和所有重定向吗?或者我是否误解了重定向/超时/上下文?

1 个答案:

答案 0 :(得分:1)

看起来每个重定向都不会重置http.Client超时。

来自net / http文档:

// Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time, any
// redirects, and reading the response body.

https://golang.org/pkg/net/http/

相关问题