'How to hook a channel into a websocket goroutine?

Golang guidelines say that the goroutine that opens and writes to a channel should close it, but then how do I hook it into a websocket (like gorilla/websocket) handler goroutine?

func (server *Server) websocketUpgrade(responseWriter http.ResponseWriter, request *http.Request) {
  // handle the request
  connection, err := server.websocketUpgrader.Upgrade(responseWriter, request, responseHeaders)
  defer connection.Close()

  // now I need a channel that the server will write to
  // so that the server can send messages to the client
  // but it can not be created here because the server has to control it (write to it and close it)

  for message := range messageChannel {
    connection.WriteMessage(websocket.BinaryMessage, message)
  }
}

What are the best practices to handle situations like this where I have no direct access to the goroutine that I need to assign a message channel for?

go


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source