Search code examples
gowebsocketchannelgorilla

gorilla websocket example with a superfluous channel?


I don't understand the reason for the channel "done", in this simple example

https://github.com/gorilla/websocket/blob/master/examples/echo/client.go

the channel is type of struct and three times used

  1. Z41 defer close(done)
  2. Z57 case <-done:
  3. Z77 case <-done:

Nobody writes into the channel. So 2. and 3. will block, as far as I can remember. I would be grateful for any explanation how this works.


Solution

  • The specification says:

    After calling close, and after any previously sent values have been received, receive operations will return the zero value for the channel's type without blocking.

    The case <-done: branches do not block after close(done) is called.

    It's common to use channel close to signal completion because the goroutine that signals completion does not need to know the number of goroutines that wait on completion. Also, channel close will never block waiting for a receiver.