title: Asynchronous messages golang
body: <p>I have a golang server doing something like this:
      package main</p>
  
  <pre><code>func main() {
      for {
          c := listener.Accept()
          go handle(c)
      }
  }
  
  ...
  func handle(c net.Conn) {
      m := readMessage(c)    // func(net.Conn)Message
      r := processMessage(m) //func(Message)Result
      sendResult(c, r)       // func(net.Conn,Result)
  }
  </code></pre>
  
  <p>Which reads and writes messages synchronously. What I need now is to send messages asynchronously through a given open connection, I know a channel can be used by I'm kind of lost.</p>
  
  <p>This is my idea:</p>
  
  <pre><code>...
  func someWhereElese(c chan Result) {
      // generate a message and a result
      r := createResultFromSomewhere()
      c &lt;- r // send the result through the channel
  }
  </code></pre>
  
  <p>And modify my handle to use that same channel instead</p>
  
  <pre><code>func handle(c net.Conn, rc chan Result) {
      m := readMessage(c)    // func(net.Conn)Message
      r := processMessage(m) //func(Message)Result
      //sendResult(c, r)       // func(net.Conn,Result)
      rc &lt;- r
  }
  </code></pre>
  
  <p>And here's where my confusion lies.</p>
  
  <p>The result channel should be created and it should have a connection where to send whatever it receives</p>
  
  <pre><code>func doSend(c net.Con, rc chan Result) {
      r := rc          // got a result channel
      sendResult(c, r) // send it through the wire
  }
  </code></pre>
  
  <p>But where should that channel be created? In the main loop?</p>
  
  <pre><code>func main() {
      ...
      for {
          c := l.Accept()
          rc := make(chan Result)
          go doSend(c, rc)
      }
  }
  </code></pre>
  
  <p>What about the read? Should it go in it's own channel/gorutine?
  If I need to broadcast to n clients, should I keep a slice of result channels? a slice of connections?</p>
  
  <p>I'm kind of confused here, but I feel I'm close.</p>