From 26720fa35eba0505e88724cb652137ace3fc3a88 Mon Sep 17 00:00:00 2001 From: minie4 Date: Tue, 29 Oct 2024 01:02:18 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=91=20Fix=20concurent=20writes=20in=20?= =?UTF-8?q?wsClients=20map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/api.go b/api.go index 9ad6d0c..f62d34b 100644 --- a/api.go +++ b/api.go @@ -3,6 +3,7 @@ package main import ( "encoding/json" "fmt" + "sync" "github.com/gin-gonic/gin" "github.com/google/uuid" @@ -15,6 +16,7 @@ type WsClient struct { SendUpdates bool } +var wsClientsMutex = new(sync.Mutex) var wsClients = make(map[*websocket.Conn]WsClient) func initApi() { @@ -428,13 +430,17 @@ func handleWs(c *gin.Context) { c.JSON(500, gin.H{"success": false, "error": "Handling websocket connection failed!"}) } + wsClientsMutex.Lock() wsClients[conn] = WsClient{SendUpdates: false} + wsClientsMutex.Unlock() for { var content WebsocketMessage jsonErr := conn.ReadJSON(&content) if jsonErr != nil { + wsClientsMutex.Lock() delete(wsClients, conn) + wsClientsMutex.Unlock() conn.Close() break } @@ -455,10 +461,12 @@ func handleWs(c *gin.Context) { case "deleteRoute": err = deleteRoute(content.UUID, content.ToUUID) case "enableUpdates": + wsClientsMutex.Lock() if clientOpts, ok := wsClients[conn]; ok { clientOpts.SendUpdates = true wsClients[conn] = clientOpts } + wsClientsMutex.Unlock() default: err = gin.H{"success": false, "error": "Method is not implemented"} } @@ -467,6 +475,7 @@ func handleWs(c *gin.Context) { } func onPortChange(port *Port) { + wsClientsMutex.Lock() for conn := range wsClients { if !wsClients[conn].SendUpdates { continue @@ -474,9 +483,11 @@ func onPortChange(port *Port) { jsonData, _ := json.Marshal(WebsocketResponse{Type: "portChange", ResponseData: port}) conn.WriteMessage(1, jsonData) } + wsClientsMutex.Unlock() } func onPortListChange() { + wsClientsMutex.Lock() for conn := range wsClients { if !wsClients[conn].SendUpdates { continue @@ -487,4 +498,5 @@ func onPortListChange() { }) conn.WriteMessage(1, jsonData) } + wsClientsMutex.Unlock() }