1
0
mirror of https://github.com/golang/go synced 2024-11-25 17:07:57 -07:00

net/http: add client option to retain the auth/cookie headers

This commit is contained in:
notrynosuccess 2021-12-27 08:36:48 +08:00
parent b357b05b70
commit 39a5762ef6

View File

@ -104,6 +104,10 @@ type Client struct {
// RoundTripper implementations should use the Request's Context // RoundTripper implementations should use the Request's Context
// for cancellation instead of implementing CancelRequest. // for cancellation instead of implementing CancelRequest.
Timeout time.Duration Timeout time.Duration
// RetainHeaders indicates whether to keep the auth/cookie headers when redirect across different primary domains.
// For example, if you want to retain the auth/cookie headers after redirecting from a.com to b.com, set it to true.
RetainHeaders bool
} }
// DefaultClient is the default Client and is used by Get, Head, and Post. // DefaultClient is the default Client and is used by Get, Head, and Post.
@ -797,12 +801,18 @@ func (c *Client) makeHeadersCopier(ireq *Request) func(*Request) {
} }
// Copy the initial request's Header values // Copy the initial request's Header values
// (at least the safe ones). // (at least the safe ones when Client.RetainHeaders is false).
if !c.RetainHeaders {
for k, vv := range ireqhdr { for k, vv := range ireqhdr {
if shouldCopyHeaderOnRedirect(k, preq.URL, req.URL) { if shouldCopyHeaderOnRedirect(k, preq.URL, req.URL) {
req.Header[k] = vv req.Header[k] = vv
} }
} }
} else {
for k, vv := range ireqhdr {
req.Header[k] = vv
}
}
preq = req // Update previous Request with the current request preq = req // Update previous Request with the current request
} }