Nevermore
Nevermore

Reputation: 7409

Context Timeout for Redirects rather than using Client Timeouts?

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?

Upvotes: 0

Views: 431

Answers (1)

eugenioy
eugenioy

Reputation: 12403

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/

Upvotes: 1

Related Questions