feat: implement stale client removal after timeout

- add goroutine to remove stale clients from the connection pool
- update client struct to track `LastPong` time
- set write deadline for websocket connections
- move package variables and const to `vars.go`
- log additional information when broadcasting errors

🤖
This commit is contained in:
Sebastian Mark 2024-11-20 14:07:00 +01:00
parent e8e65c4f3a
commit ab2e8c161d
7 changed files with 75 additions and 21 deletions

View file

@ -1,9 +1,9 @@
package models
import (
"github.com/gorilla/websocket"
"time"
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
"github.com/gorilla/websocket"
)
// Represents a command from the client (start/stop)
@ -15,17 +15,13 @@ type ClientCommand struct {
// Represents a single client
type WebsocketClient struct {
Conn *websocket.Conn
RealIP string
Conn *websocket.Conn
LastPong time.Time
RealIP string
}
// Sends a message to the websocket.
// Automatically locks and unlocks the client mutex, to ensure that only one goroutine can write at a time.
func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
err := c.Conn.WriteMessage(messageType, data)
if err != nil {
helper.Logger.Error("Error writing to WebSocket:", "msg", err)
c.Conn.Close() // Close the connection on error
}
return err
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
return c.Conn.WriteMessage(messageType, data)
}