Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Created September 7, 2022 13:27
Show Gist options
  • Save percybolmer/3c8af5b1a744a9385f99fe078d94e67e to your computer and use it in GitHub Desktop.
Save percybolmer/3c8af5b1a744a9385f99fe078d94e67e to your computer and use it in GitHub Desktop.
write websockets messages
// writeMessages is a process that listens for new messages to output to the Client
func (c *Client) writeMessages() {
defer func() {
// Graceful close if this triggers a closing
c.manager.removeClient(c)
}()
for {
select {
case message, ok := <-c.egress:
// Ok will be false Incase the egress channel is closed
if !ok {
// Manager has closed this connection channel, so communicate that to frontend
if err := c.connection.WriteMessage(websocket.CloseMessage, nil); err != nil {
// Log that the connection is closed and the reason
log.Println("connection closed: ", err)
}
// Return to close the goroutine
return
}
// Write a Regular text message to the connection
if err := c.connection.WriteMessage(websocket.TextMessage, message); err != nil {
log.Println(err)
}
log.Println("sent message")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment