ChronoTomato/internal/websocket/receive.go
Sebastian Mark bcda687c5e refactor: websocket client and closure variable
- update comments
- move `Done` variable to vars.go
- move `Connected()` method

🤖
2024-11-21 12:28:36 +01:00

47 lines
1 KiB
Go

package websocket
import (
"encoding/json"
"time"
"github.com/gorilla/websocket"
GoTomato "git.smsvc.net/pomodoro/GoTomato/pkg/models"
)
// 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
defer close(Done)
for {
c.Conn.SetReadDeadline(time.Now().Add(10 * time.Second))
_, message, err := c.Conn.ReadMessage()
if err != nil {
c.LastErr = err
// On normal closure exit gracefully
if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
return
}
// reset connection and reconnect
c.Conn = nil
pw := c.Password
for !c.Connected() {
channel <- serverMessage // send last known ServerMessage to update view
time.Sleep(time.Second)
*c = Connect(c.Server)
}
c.Password = pw
continue
}
err = json.Unmarshal(message, &serverMessage)
c.LastErr = err
channel <- serverMessage
}
}