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



我使用显式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)

这是否包含同一超时中的请求和所有重定向?还是我误解了重定向/超时/上下文?

看起来不是每个重定向都会重置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/

最新更新