Sebastian Mark
05e8bf5854
- add `Connected()` method for client - add `LastErr` field to GoTomatoClient - replace error logging by updating `LastErr` field - modify methods to use pointer receivers for Client - add `prevMessage` variable to store the last received server message - show connect status in TUI - use EnterAltScreen instead of ClearScreen
47 lines
1,003 B
Go
47 lines
1,003 B
Go
package websocket
|
|
|
|
import (
|
|
"encoding/json"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
GoTomato "git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
|
)
|
|
|
|
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, prevMessage GoTomato.ServerMessage
|
|
|
|
defer close(Done)
|
|
|
|
for {
|
|
_, message, err := c.Conn.ReadMessage()
|
|
if err != nil {
|
|
// On normal closure exit gracefully
|
|
if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
|
|
return
|
|
}
|
|
|
|
// Try to reconnect on unexpected disconnect
|
|
for {
|
|
channel <- prevMessage // send previous ServerMessage to update view
|
|
time.Sleep(time.Second)
|
|
*c = Connect(c.Server)
|
|
if c.Connected() {
|
|
break
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
|
|
err = json.Unmarshal(message, &serverMessage)
|
|
c.LastErr = err
|
|
|
|
channel <- serverMessage
|
|
prevMessage = serverMessage
|
|
}
|
|
}
|