Timeouts
timeouts are important for programs that connect to external resources or that otherwise need to limit execution time.
Implementing timeouts in Go is easy and elegant thanks to channels and select.
For our example, suppose we are executing an outer call that returns its result on a c1 channel after 2s. Note that the channel is stored in buffer, so sending in goroutine is non-blocking.
This is a common pattern to prevent goroutine leaks if the channel is never read.
Here is the implementation selection of a timeout. res := <-c1 waits for the result and <-time.After waits for a value to be sent after the 1s timeout.
Since the selection continues with the first receive that is ready, we will use the timeout case if the operation takes more than the allowed 1s.