From 0ee955189c7cdb4156ced500d9d582022708857d Mon Sep 17 00:00:00 2001 From: Sebastian Mark Date: Wed, 30 Oct 2024 10:17:24 +0100 Subject: [PATCH] feat: update client management to use local address as identifier MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - change Clients map to use net.Addr as the key type - update `HandleConnection()` to store clients using LocalAddr - modify `handleClientCommands()` to delete clients by LocalAddr 🤖 --- internal/websocket/client_commands.go | 2 +- internal/websocket/handle_connection.go | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/internal/websocket/client_commands.go b/internal/websocket/client_commands.go index 59e603a..b38e55b 100644 --- a/internal/websocket/client_commands.go +++ b/internal/websocket/client_commands.go @@ -18,7 +18,7 @@ func handleClientCommands(c models.WebsocketClient) { _, message, err := ws.ReadMessage() if err != nil { log.Info("Client disconnected:", "msg", err, "host", ws.NetConn().RemoteAddr(), "clients", len(Clients)-1) - delete(Clients, ws) + delete(Clients, ws.LocalAddr()) break } diff --git a/internal/websocket/handle_connection.go b/internal/websocket/handle_connection.go index dc5ad1c..b7b240f 100644 --- a/internal/websocket/handle_connection.go +++ b/internal/websocket/handle_connection.go @@ -3,14 +3,15 @@ package websocket import ( "github.com/charmbracelet/log" "github.com/gorilla/websocket" + "net" "net/http" "sync" "git.smsvc.net/pomodoro/GoTomato/pkg/models" ) -// Clients is a map of connected WebSocket clients, where each client is represented by the Client struct -var Clients = make(map[*websocket.Conn]*models.WebsocketClient) +// 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) var mu sync.Mutex // Mutex to protect access to the Clients map // Upgrade HTTP requests to WebSocket connections @@ -35,7 +36,7 @@ func HandleConnection(w http.ResponseWriter, r *http.Request) { Conn: ws, } mu.Lock() - Clients[ws] = &client + Clients[ws.LocalAddr()] = &client mu.Unlock() // Listen for commands from the connected client