2024-10-19 09:47:56 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/gorilla/websocket"
|
2024-10-30 09:17:24 +00:00
|
|
|
"net"
|
2024-10-19 09:47:56 +00:00
|
|
|
"net/http"
|
2024-10-20 18:51:21 +00:00
|
|
|
"sync"
|
2024-11-20 19:31:24 +00:00
|
|
|
"time"
|
2024-10-28 08:33:05 +00:00
|
|
|
|
2024-11-04 19:33:25 +00:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
2024-10-28 08:33:05 +00:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
2024-10-19 09:47:56 +00:00
|
|
|
)
|
|
|
|
|
2024-10-30 09:17:24 +00:00
|
|
|
// Clients is a map of connected WebSocket clients, where each client is represented by the WebsocketClient struct
|
|
|
|
var Clients = make(map[net.Addr]*models.WebsocketClient)
|
2024-10-20 18:51:21 +00:00
|
|
|
var mu sync.Mutex // Mutex to protect access to the Clients map
|
|
|
|
|
2024-10-30 06:37:14 +00:00
|
|
|
// Upgrade HTTP requests to WebSocket connections
|
2024-10-19 09:47:56 +00:00
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
CheckOrigin: func(r *http.Request) bool { return true },
|
|
|
|
}
|
|
|
|
|
2024-11-20 20:22:46 +00:00
|
|
|
// initialize a new WebsocketClient
|
|
|
|
func newWebsocketClient(ws *websocket.Conn, address string) models.WebsocketClient {
|
|
|
|
wsclient := models.WebsocketClient{
|
|
|
|
Conn: ws,
|
|
|
|
LastPong: time.Now(),
|
|
|
|
RealIP: address,
|
|
|
|
}
|
|
|
|
|
|
|
|
wsclient.Conn.SetPongHandler(func(appData string) error {
|
|
|
|
wsclient.LastPong = time.Now()
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
return wsclient
|
|
|
|
}
|
|
|
|
|
2024-10-30 06:37:14 +00:00
|
|
|
// Upgrades HTTP requests to WebSocket connections and manages the client lifecycle
|
2024-10-29 17:49:00 +00:00
|
|
|
func HandleConnection(w http.ResponseWriter, r *http.Request) {
|
2024-10-19 09:47:56 +00:00
|
|
|
// Upgrade initial GET request to a WebSocket
|
|
|
|
ws, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
2024-11-04 19:33:25 +00:00
|
|
|
helper.Logger.Error("WebSocket upgrade error:", "msg", err)
|
2024-10-19 09:47:56 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
defer ws.Close()
|
|
|
|
|
|
|
|
// Register the new client
|
2024-11-20 20:22:46 +00:00
|
|
|
client := newWebsocketClient(ws, r.RemoteAddr)
|
|
|
|
|
2024-10-30 07:09:41 +00:00
|
|
|
mu.Lock()
|
2024-10-30 09:17:24 +00:00
|
|
|
Clients[ws.LocalAddr()] = &client
|
2024-10-20 15:31:05 +00:00
|
|
|
mu.Unlock()
|
2024-10-19 09:47:56 +00:00
|
|
|
|
2024-11-04 19:33:25 +00:00
|
|
|
helper.Logger.Info("Client connected", "host", client.RealIP, "clients", len(Clients))
|
2024-11-03 09:00:14 +00:00
|
|
|
|
2024-10-19 09:47:56 +00:00
|
|
|
// Listen for commands from the connected client
|
2024-10-30 07:09:41 +00:00
|
|
|
handleClientCommands(client)
|
2024-10-19 09:47:56 +00:00
|
|
|
}
|