When using roundTripWithOptionalFollowRedirect, note that it is the responsibility of the caller to close the response body.
(ctx context.Context, u string, maxRedirects int, opts ...RequestOption)
| 2040 | // When using roundTripWithOptionalFollowRedirect, note that it |
| 2041 | // is the responsibility of the caller to close the response body. |
| 2042 | func (c *Client) roundTripWithOptionalFollowRedirect(ctx context.Context, u string, maxRedirects int, opts ...RequestOption) (*http.Response, error) { |
| 2043 | req, err := c.NewRequest(ctx, "GET", u, nil, opts...) |
| 2044 | if err != nil { |
| 2045 | return nil, err |
| 2046 | } |
| 2047 | |
| 2048 | var resp *http.Response |
| 2049 | // Use http.DefaultTransport if no custom Transport is configured |
| 2050 | if c.client.Transport == nil { |
| 2051 | resp, err = http.DefaultTransport.RoundTrip(req) |
| 2052 | } else { |
| 2053 | resp, err = c.client.Transport.RoundTrip(req) |
| 2054 | } |
| 2055 | if err != nil { |
| 2056 | return nil, err |
| 2057 | } |
| 2058 | |
| 2059 | // If redirect response is returned, follow it |
| 2060 | if maxRedirects > 0 && resp.StatusCode == http.StatusMovedPermanently { |
| 2061 | _ = resp.Body.Close() |
| 2062 | u = resp.Header.Get("Location") |
| 2063 | if err := c.checkRedirectHost(u); err != nil { |
| 2064 | return nil, err |
| 2065 | } |
| 2066 | resp, err = c.roundTripWithOptionalFollowRedirect(ctx, u, maxRedirects-1, opts...) |
| 2067 | } |
| 2068 | return resp, err |
| 2069 | } |
| 2070 | |
| 2071 | // checkRedirectHost returns an error if the redirect target is on a different |
| 2072 | // host than the client's configured BaseURL. This prevents credentials attached |