Handling Timeouts

Because these channels use the network, there is alwasy the possibility of network errors leading to timeouts.
Andrew Gerrand points out a solution using timeouts: “[Set up a timeout channel.] We can then use a select statement to receive from either ch or timeout. If nothing arrives on ch after one second, the timeout case is selected and the attempt to read from ch is abandoned.”

  1. timeout := make(chan bool, 1)
  2. go func() {
  3. time.Sleep(1e9) // one second
  4. timeout <- true
  5. }()
  6. select {
  7. case <- ch:
  8. // a read from ch has occurred
  9. case <- timeout:
  10. // the read from ch has timed out
  11. }