by haiku2077 · 1y ago · 0 comments
I believe this is considered a bad practice: the general attitude is that the only sane use case for values in context.Context is tracing data, and all other data should he explicitly passed via arguments.
The only place I’ve encountered this pattern is in chromedp, the go wrapper for the chrome headless browser driver. Its API… isn’t good.
Most methods you use are package globals that take a context.Context as a first parameter. But you have to understand that this context is a _special_ one: you can’t pass any old context like context.Background(), you must pass a context you got from one of the factory methods.
If you want to specify a timeout, you use context.WithTimeout. Clever I guess, but that’s the only setting that works like that.
It’s essentially a void*.
It's totally fine to put multiple values into a different data bag type that has explicit, typed fields. For example, the Echo framework has its own strongly typed and extensible Context interface for request scoped data: https://pkg.go.dev/github.com/labstack/echo#Context
The data passing maybe, not sure how you lose type safety. The value comes from the context with the right type just fine. The stuff that I'm attaching to the context are effectively globals just that this way you can enable proper isolation in tests and else.
From my limited experience with echo, the context there is not at all the same thing.