Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Created September 7, 2022 06:00
Show Gist options
  • Save percybolmer/0576d6034604fdecff7320a01fc49a58 to your computer and use it in GitHub Desktop.
Save percybolmer/0576d6034604fdecff7320a01fc49a58 to your computer and use it in GitHub Desktop.
// readMessages will start the client to read messages and handle them
// appropriatly.
// This is suppose to be ran as a goroutine
func (c *Client) readMessages() {
defer func() {
// Graceful Close the Connection once this
// function is done
c.manager.removeClient(c)
}()
// Loop Forever
for {
// ReadMessage is used to read the next message in queue
// in the connection
messageType, payload, err := c.connection.ReadMessage()
if err != nil {
// If Connection is closed, we will Recieve an error here
// We only want to log Strange errors, but not simple Disconnection
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error reading message: %v", err)
}
break // Break the loop to close conn & Cleanup
}
log.Println("MessageType: ", messageType)
log.Println("Payload: ", string(payload))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment