title: Broadcast a channel through multiple channel in Go
body: <p>I would like to broadcast data received from a channel to a list of channel. The list of channel is dynamic an can be modified during the run phase.</p>
  
  <p>As a new developper in <code>Go</code>, I wrote this code. I found it quite heavy for what I want. Is-there a better way to do this?</p>
  
  <pre><code>package utils
  
  import "sync"
  
  // StringChannelBroadcaster broadcasts string data from a channel to multiple channels
  type StringChannelBroadcaster struct {
      Source      chan string
      Subscribers map[string]*StringChannelSubscriber
      stopChannel chan bool
      mutex       sync.Mutex
      capacity    uint64
  }
  
  // NewStringChannelBroadcaster creates a StringChannelBroadcaster
  func NewStringChannelBroadcaster(capacity uint64) (b *StringChannelBroadcaster) {
      return &amp;StringChannelBroadcaster{
          Source:      make(chan string, capacity),
          Subscribers: make(map[string]*StringChannelSubscriber),
          capacity:    capacity,
      }
  }
  
  // Dispatch starts dispatching message
  func (b *StringChannelBroadcaster) Dispatch() {
      b.stopChannel = make(chan bool)
      for {
          select {
          case val, ok := &lt;-b.Source:
              if ok {
                  b.mutex.Lock()
                  for _, value := range b.Subscribers {
                      value.Channel &lt;- val
                  }
                  b.mutex.Unlock()
              }
          case &lt;-b.stopChannel:
              return
          }
      }
  }
  
  // Stop stops the Broadcaster
  func (b *StringChannelBroadcaster) Stop() {
      close(b.stopChannel)
  }
  
  // StringChannelSubscriber defines a subscriber to a StringChannelBroadcaster
  type StringChannelSubscriber struct {
      Key     string
      Channel chan string
  }
  
  // NewSubscriber returns a new subsriber to the StringChannelBroadcaster
  func (b *StringChannelBroadcaster) NewSubscriber() *StringChannelSubscriber {
      key := RandString(20)
      newSubscriber := StringChannelSubscriber{
          Key:     key,
          Channel: make(chan string, b.capacity),
      }
      b.mutex.Lock()
      b.Subscribers[key] = &amp;newSubscriber
      b.mutex.Unlock()
  
      return &amp;newSubscriber
  }
  
  // RemoveSubscriber removes a subscrber from the StringChannelBroadcaster
  func (b *StringChannelBroadcaster) RemoveSubscriber(subscriber *StringChannelSubscriber) {
      b.mutex.Lock()
      delete(b.Subscribers, subscriber.Key)
      b.mutex.Unlock()
  }
  </code></pre>
  
  <p>Thank you,</p>
  
  <p>Julien</p>