GoTomato/pkg/models/client.go
Sebastian Mark 4471c86a0c fix: prevent concurrent write to websocket connection
- refactor client handling and message broadcasting
- replace Client struct
- implement SendMessage method in Client struct for safer message sending
- update client map to use *models.Client instead of bool
- adjust BroadcastMessage and RunPomodoroTimer functions to use new client type

🤖
2024-10-20 11:06:37 +02:00

30 lines
666 B
Go

package models
import (
"github.com/gorilla/websocket"
"log"
"sync"
)
// ClientCommand represents a command from the client (start/stop).
type ClientCommand struct {
Command string `json:"command"`
}
type Client struct {
Conn *websocket.Conn
Mutex sync.Mutex
}
// It automatically locks and unlocks the mutex to ensure that only one goroutine can write at a time.
func (c *Client) SendMessage(messageType int, data []byte) error {
c.Mutex.Lock()
defer c.Mutex.Unlock()
err := c.Conn.WriteMessage(messageType, data)
if err != nil {
log.Printf("Error writing to WebSocket: %v", err)
c.Conn.Close() // Close the connection on error
}
return err
}