2024-10-19 09:47:56 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
2024-10-21 06:16:26 +00:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/internal/broadcast"
|
2024-10-20 09:06:37 +00:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
2024-10-19 09:47:56 +00:00
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2024-10-20 18:51:21 +00:00
|
|
|
"sync"
|
2024-10-19 09:47:56 +00:00
|
|
|
)
|
|
|
|
|
2024-10-20 18:51:21 +00:00
|
|
|
var mu sync.Mutex // Mutex to protect access to the Clients map
|
|
|
|
|
2024-10-19 09:47:56 +00:00
|
|
|
// Upgrader to upgrade HTTP requests to WebSocket connections
|
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
CheckOrigin: func(r *http.Request) bool { return true },
|
|
|
|
}
|
|
|
|
|
|
|
|
// HandleConnections upgrades HTTP requests to WebSocket connections and manages the client lifecycle.
|
|
|
|
func HandleConnections(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// Upgrade initial GET request to a WebSocket
|
|
|
|
ws, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("WebSocket upgrade error: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer ws.Close()
|
|
|
|
|
|
|
|
// Register the new client
|
2024-10-20 15:31:05 +00:00
|
|
|
mu.Lock()
|
2024-10-21 06:16:26 +00:00
|
|
|
broadcast.Clients[ws] = &models.Client{
|
2024-10-20 09:06:37 +00:00
|
|
|
Conn: ws, // Store the WebSocket connection
|
|
|
|
}
|
2024-10-20 15:31:05 +00:00
|
|
|
mu.Unlock()
|
2024-10-19 09:47:56 +00:00
|
|
|
|
|
|
|
// Listen for commands from the connected client
|
|
|
|
handleClientCommands(ws)
|
|
|
|
}
|