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

huangapple go评论90阅读模式
英文:

Context Timeout for Redirects rather than using Client Timeouts?

问题

我从客户端执行了一个明确指定了http.Client.Timeout的HTTP请求。

client := http.Client{
    Timeout: timeout, // 5秒
}

httpResponse, err := client.Do(httpRequest)

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

据我了解,每个重定向都会重新启动超时计时器,所以5秒的超时时间将变为五秒 * 重定向次数

是否可以**将超时时间传递给context.Context**呢?

ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
// 需要取消吗?
httpRequest.WithContext(ctx)
httpResponse, err := client.Do(httpRequest)

这样做是否可以在同一个超时时间内包含请求和所有重定向?或者我对重定向、超时和上下文的理解有误?

英文:

I perform an HTTP request from a client with an explicit http.Client.Timeout

client := http.Client{
	Timeout: timeout, // 5 seconds
}

httpResponse, err := client.Do(httpRequest)

But this client will perform a series of redirects (I'm not sure how many).

From what I understand, each redirect will restart the timeout, so the timeout of 5 seconds will be five-seconds * num-of-redirects.

Is it possible to rather pass in the timeout inside a context.Context?

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

Would this encompass the request and all redirects in the same timeout? Or do I misunderstand redirects/timeouts/contexts?

答案1

得分: 1

根据net/http文档,似乎每次重定向不会重置http.Client的超时时间。

// Timeout指定此Client发出的请求的时间限制。
// 超时包括连接时间、任何重定向和读取响应体。

详细信息请参考:https://golang.org/pkg/net/http/

英文:

It does not look like each redirect will reset the http.Client time out.

From the net/http documentation:

// 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/

huangapple
  • 本文由 发表于 2017年5月21日 23:22:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/44098526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定