GoTomato/pkg/models/client.go
2024-11-21 18:50:00 +01:00

40 lines
1.1 KiB
Go

package models
import (
"time"
"github.com/gorilla/websocket"
)
const TIMEOUT = 10
// Represents a command from the client (start/stop)
type ClientCommand struct {
Command string `json:"command"` // Command send to the server
Password string `json:"password"` // Pomodoro control password
Settings PomodoroConfig `json:"settings"` // Pomodoro config
}
// Represents a single client
type WebsocketClient struct {
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 {
c.Conn.SetPongHandler(func(appData string) error {
c.LastPong = time.Now()
return nil
})
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
err := c.Conn.WriteMessage(websocket.PingMessage, nil)
if err != nil {
return err
}
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
return c.Conn.WriteMessage(messageType, data)
}