title: How to multiplex channel output in go
body: <p>I'm looking for a solution to multiplex some channel output in go.</p>
  
  <p>I have a source of data which is a read from an <code>io.Reader</code> that I send to a single channel. On the other side I have a websocket request handler that reads from the channel. Now it happens that two clients create a websocket connection, both reading from the same channel but each of them only getting a part of the messages.</p>
  
  <p><strong>Code example (simplified):</strong></p>
  
  <pre><code>func (b *Bootloader) ReadLog() (&lt;-chan []byte, error) {
      if b.logCh != nil {
          logrus.Warn("ReadLog called while channel already exists!")
          return b.logCh, nil // This is where we get problems
      }
  
      b.logCh = make(chan []byte, 0)
  
      go func() {
          buf := make([]byte, 1024)
          for {
              n, err := b.p.Read(buf)
  
              if err == nil {
                  msg := make([]byte, n)
                  copy(msg, buf[:n])
                  b.logCh &lt;- msg
              } else {
                  break
              }
          }
  
          close(b.logCh)
          b.logCh = nil
      }()
  
      return b.logCh, nil
  }
  </code></pre>
  
  <p>Now when <code>ReadLog()</code> is called twice, the second call just returns the channel created in the first call, which leads to the problem explained above.</p>
  
  <p><strong>The question is:</strong> How to do proper multiplexing?</p>
  
  <p>Is it better/easier/more ideomatic to care about the multiplexing on the sending or receiving site?</p>
  
  <p>Should I hide the channel from the receiver and work with callbacks?</p>
  
  <p>I'm a little stuck at the moment. Any hints are welcome.</p>