Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Created September 11, 2022 05:33
Show Gist options
  • Save percybolmer/0843c7be96aa2c604c8371bd5ea0d7d1 to your computer and use it in GitHub Desktop.
Save percybolmer/0843c7be96aa2c604c8371bd5ea0d7d1 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)
}()
// Configure Wait time for Pong response, use Current time + pongWait
// This has to be done here to set the first initial timer.
if err := c.connection.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
log.Println(err)
return
}
// Configure how to handle Pong responses
c.connection.SetPongHandler(c.pongHandler)
// Loop Forever
for {
// ReadMessage is used to read the next message in queue
// in the connection
_, 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 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
}
// Marshal incoming data into a Event struct
var request Event
if err := json.Unmarshal(payload, &request); err != nil {
log.Printf("error marshalling message: %v", err)
break // Breaking the connection here might be harsh xD
}
// Route the Event
if err := c.manager.routeEvent(request, c); err != nil {
log.Println("Error handeling Message: ", err)
}
}
}
// pongHandler is used to handle PongMessages for the Client
func (c *Client) pongHandler(pongMsg string) error {
// Current time + Pong Wait time
log.Println("pong")
return c.connection.SetReadDeadline(time.Now().Add(pongWait))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment