The http.Request struct had a Clone method added in go 1.13, prompted by this issue: #23544. At that time, I believe the documentation for WithContext was updated to suggest that most uses of that method could be replaced with Clone.
@bradfitz I just came across Clone as a first time user of contexts within net/http. I had a question about this bit of documentation on WithContext:
...To change the context of a request (such as an incoming) you then also want to modify to send back out, use Request.Clone. Between those two uses, it's rare to need WithContext.
I wanted to ask if Clone should be preferred over WithContext in all situations. Specifically I'm writing a server middleware and only need to annotate a request (adding a logged in user) so it can be used by other handlers.
Is WithContext not appropriate for this situation?
And this has come up occasionally in Slack as well, with people writing very simple middleware that wrap http.Handler and just stick a value into the context on the request using WithContext. An extremely simple version, for which Clone seems like overkill, might be:
So this issue is mostly asking: is this usage of WithContext in this sort of middleware context correct, and furthermore can we augment the WithContext documentation block to be less prescriptive that Clone is the obvious way to go, and that there are plenty of value use-cases for WithContext, especially when you're not looking to "reuse" the request to make a subsequent request?
The text was updated successfully, but these errors were encountered: