2017-05-21 15 views
0

我執行來自客戶端的HTTP請求有一個明確的http.Client.Timeout重定向的上下文超時而不是使用客戶端超時?

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

它看起來並不像每個重定向都會重置http.Client超時。

從淨值/ 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/

+0

會用CTX工作,而不是呢? – Nevermore

+1

看起來它的工作也是如此,請參閱此相關問題的示例和進一步解釋:http://stackoverflow.com/questions/43321894/context-timeout-implementation-on-every-request-using-golang – eugenioy