GoTomato/pkg/models/client.go

32 lines
867 B
Go

package models
import (
"github.com/charmbracelet/log"
"github.com/gorilla/websocket"
"sync"
)
// ClientCommand represents a command from the client (start/stop).
type ClientCommand struct {
Command string `json:"command"` // comman send to the server
Password string `json:"password"` // pomodoro control password
Settings PomodoroConfig `json:"settings"` // pomodoro config
}
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.Error("Error writing to WebSocket:", "msg", err)
c.Conn.Close() // Close the connection on error
}
return err
}