Understanding Golang Context timeout
A context
is best used to manage the lifecycle of something. Therefore if you are doing something (e.g., processing a file), then you should be checking the context to ensure the process hasn't been processed.
There are two ways to check if a context
has been cancelled or timed out:
Context.Done()
- This returns a channel that will be closed when the context is cancelled.Context.Err()
- This will return an error if the context is cancelled.
Pick the one that best suits your needs. If you are doing things with channels, then using the context.Done()
in a select
works well. If you are using a for
loop while reading an io.Reader
, then checking context.Err()
is easier.
All that being said, if you are starting something that also takes a context, you should always use the context you already have if you would want that new "thing" to be cancelled if you were cancelled.
The select
code in the second part of your question is what the code in the Connect
method might look like. There it is checking whether the ctx.Done()
is ready to send. If it is, then the context was cancelled either because the timeout occurred, or because cancel()
was called.
errors are values. Treat them as such. If it is important for you to understand the cause of the error (network down? unexpected data? timeout?) then you should do the check and act accordingly. If recovery from the error regardless of the cause is the same, then checking the error is not as important.