ChronoTomato/internal/websocket/receive.go

42 lines
957 B
Go
Raw Normal View History

2024-10-22 11:13:41 +00:00
package websocket
import (
"encoding/json"
"github.com/gorilla/websocket"
"git.smsvc.net/pomodoro/ChronoTomato/internal/helper"
GoTomato "git.smsvc.net/pomodoro/GoTomato/pkg/models"
2024-10-22 11:13:41 +00:00
)
var Done = make(chan struct{})
// Receives websocket messages and writes them to a channel.
// Closes the channel if websocket closes.
func (c Client) ProcessServerMessages(channel chan<- GoTomato.ServerMessage) {
var serverMessage GoTomato.ServerMessage
2024-10-22 11:13:41 +00:00
defer close(Done)
for {
_, message, err := c.Conn.ReadMessage()
2024-10-22 11:13:41 +00:00
if err != nil {
if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
// Ignore normal closure and exit gracefully
return
}
// Log any other errors
helper.Logger.Error("Read error!", "reason", err)
close(channel)
2024-10-22 11:13:41 +00:00
return
}
err = json.Unmarshal(message, &serverMessage)
2024-10-22 11:13:41 +00:00
if err != nil {
helper.Logger.Error("Error unmarshalling!", "reason", err)
2024-10-22 11:13:41 +00:00
continue
}
channel <- serverMessage
2024-10-22 11:13:41 +00:00
}
}