context
A context carries cancellation and a deadline. Functions that may wait take it as the first argument.
context.Context is the standard way to say "this work may be stopped". A context has a deadline, cancellation, and the channel Done().
ctx, cancel := context.WithTimeout(parent, 2*time.Second)
defer cancel()
cancel is always called, otherwise the timer and the related resources live until the deadline. defer next to the creation is the right pair. context.Background() is the root for main and for tests. context.TODO() is an honest stub while there is nowhere to take a context from. Do not store a context in a struct for long. Pass it as an argument: the first position, under the name ctx.
Cancellation is cooperative. http.NewRequestWithContext will interrupt a request, because the client looks at the context. Your loop over a slice will not be interrupted until you yourself look at ctx.Err(). The check is cheap at the start of an iteration if the body of the iteration is short. Between steps that have already gone to the network, the library will see the cancellation if you passed it the same ctx.
context.WithValue is for request data that truly passes through: a trace identifier, the user after authentication. Do not put optional function parameters, the database, and the logger there "so you do not have to carry arguments". Values in a context are not visible in the signature. They are easy to forget to put in, and a test silently receives nil.
The function that created a child context is responsible for cancel. The function that received a context does not cancel the parent: it only listens. Canceling someone else's request from above breaks the caller.
Practice
Where the argument goes
By convention, where is
context.Contextplaced among the parameters of a function?- Last, after error
- First
- Only in the server struct
- In the package context through a global variable
Why the context is closed
Write
DoneReason(ctx context.Context) string. If the context has not finished yet, returnopen. If it was canceled, returncancel. If the deadline has passed, returndeadline.What goes into Value
What is appropriate to pass through
context.WithValue?- The trace identifier of the request
- The pool of database connections
- The fact of cancellation. Done already carries it
- A required user id, without which the function makes no sense and which is easy to make an ordinary argument