2 ms·
Rule 3: Don’t store contexts - What about this: https://github.com/golang/go/blob/master/src/net/http/client.go#L668C4-L668C24 https://github.com/golang/go/blob
by italicmew123 3y ago
Rule 3: Don’t store contexts - What about this: https://github.com/golang/go/blob/master/src/net/http/client.go#L668C4-L668C24 https://github.com/golang/go/blob/master/src/net/http/client...
req = &Request{
Method: redirectMethod,
Response: resp,
URL: u,
Header: make(Header),
Host: host,
Cancel: ireq.Cancel,
ctx: ireq.ctx,
}
Isn't this considered storing the context?
- maxwellg 3y agoYep - (my understanding is) the Go HTTP stdlib module predates the concept of context in Golang, so the implementation was bolted on to ensure backwards compatibility. NewRequestWithContext was only added in Go 1.13 [1]. Previously, requests were cancelled manually with CancelReqest [2]. This is an unfortunate wart of the language - it means it's very easy to accidentally spin up a new Request which doesn't inherit the parent context by calling NewRequest instead. And adding the context via the builder pattern means it's possible to introduce the storage bugs described in the article. My preferred way to consume a context would be to take it in when the work is actually about to be performed - e.g. client.Do(ctx, reqest) 1 - https://pkg.go.dev/net/http#NewRequestWithContext https://pkg.go.dev/net/http#NewRequestWithContext 2 - https://pkg.go.dev/net/http#Transport.CancelRequest https://pkg.go.dev/net/http#Transport.CancelRequest
- __turbobrew__ 3y agoYea I don’t really agree with the rule that goroutines shouldn’t be started in libraries either. For example, say you are building a library to send metrics to a metrics collector. For me it makes sense that your metrics library contains a buffer of metrics which it batches data together and sends to the metrics collector asynchronously. This would be implemented as having a library goroutine which batches and sends metrics data. I guess in theory your library could have a ‘Flush’ method and then if the application wants async flushing the application can start a goroutine which periodically calls flush. But then the application needs to know the ideal frequency to flush, how to handle failures to flush, how to backoff, etc. These things are probably better done by the library writer.
- Philip-J-Fry 3y agohttps://go.dev/blog/context-and-structs https://go.dev/blog/context-and-structs >Exception to the rule: preserving backwards compatibility See that section of the blog post. It talks about the different approaches they could have took and why they chose the one they did.