Comment by ozgrakkurt
Comment by ozgrakkurt a day ago
soo, a context?
Comment by ozgrakkurt a day ago
soo, a context?
If the struct has a well-scoped and short-lived lifecycle, then it is actually better to put the context in the struct. Many Go libraries including the stdlib do this despite not being "best practice".
An exception to the short-lived rule is to put context in your service struct and pass it as the base context when constructing the HTTP server, so that when you get a service shutdown signal, one can cancel requests gracefully.
It's well scoped, but not short lived; it's an SQLite connection.
But the API surface is huge, with 100s of methods on the connection and derived objects, with it being unclear which might block and be worthy of asynchronous cancellation. You never know when pulling an additional column if that one might be an overflow text/blob that does additional IO.
The solution, while not amazing is a method that you use like this:
old := conn.SetInterrupt(ctx)
defer conn.SetInterrupt(old)
This changes the “interrupt” context for the duration of your function scope, and covers all potentially blocking calls that you might make. Also, from the name, it's quite clear that this context is used only for interruption/cancellation (interrupt is the SQLite name for this, which I try to adhere to).
You can take that view, yes.
But if you store your context in a struct (which is not the recommend “best practice” – but which you can do) it's no longer a function coloring issue.
I do that in on of my libraries and I feel that it's the right call (for that library).