Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

net/http: avoid copy if WithContext attempts to set exact same *ctx object #44525

kevinburke1 opened this issue Feb 23, 2021 · 0 comments


Copy link

@kevinburke1 kevinburke1 commented Feb 23, 2021

Prior to NewRequestWithContext a lot of code looked like:

req, _ := http.NewRequest("GET", "", nil)
req = req.WithContext(ctx)

Now that NewRequestWithContext is a thing, existing code may get ported - incorrectly - as:

req, _ := http.NewRequestWithContext(ctx, "GET", "", nil)
req = req.WithContext(ctx)

Under the hood, WithContext does this:

func (r *Request) WithContext(ctx context.Context) *Request {
	if ctx == nil {
		panic("nil context")
	r2 := new(Request)
	*r2 = *r
	r2.ctx = ctx
	r2.URL = cloneURL(r.URL) // legacy behavior; TODO: try to remove. Issue 23544
	return r2

Basically, my suggestion is to check if the incoming ctx and the existing r.ctx point to the same value in memory, then avoid the copy to r2 and just return r in that case.

In theory this is a breaking change of behavior if someone is doing e.g.

req2 := req.WithContext(ctx)

and then using both req and req2 though I don't think the behavior is very well defined if you do that.

@seankhliao seankhliao added the NeedsInvestigation label Feb 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet

No branches or pull requests

2 participants