From 35681102b4fa4353f8bf9f297ad40037d175680d Mon Sep 17 00:00:00 2001 From: minie4 Date: Mon, 16 Dec 2024 21:26:14 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=91=20Fix=20concurrent=20writes=20in?= =?UTF-8?q?=20websocket=20connection?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/api.go b/api.go index f62d34b..9d4825d 100644 --- a/api.go +++ b/api.go @@ -14,6 +14,7 @@ var upgrader = websocket.Upgrader{} type WsClient struct { SendUpdates bool + WriteMutex *sync.Mutex } var wsClientsMutex = new(sync.Mutex) @@ -405,7 +406,9 @@ func wsSendRes(conn *websocket.Conn, res gin.H, err gin.H, request *WebsocketMes RequestMethod: request.Method, ResponseData: err, }) + wsClients[conn].WriteMutex.Lock() conn.WriteMessage(1, data) + wsClients[conn].WriteMutex.Unlock() return } @@ -420,7 +423,9 @@ func wsSendRes(conn *websocket.Conn, res gin.H, err gin.H, request *WebsocketMes } data, _ := json.Marshal(response) + wsClients[conn].WriteMutex.Lock() conn.WriteMessage(1, data) + wsClients[conn].WriteMutex.Unlock() } func handleWs(c *gin.Context) { @@ -431,7 +436,7 @@ func handleWs(c *gin.Context) { } wsClientsMutex.Lock() - wsClients[conn] = WsClient{SendUpdates: false} + wsClients[conn] = WsClient{SendUpdates: false, WriteMutex: new(sync.Mutex)} wsClientsMutex.Unlock() for { @@ -481,7 +486,9 @@ func onPortChange(port *Port) { continue } jsonData, _ := json.Marshal(WebsocketResponse{Type: "portChange", ResponseData: port}) + wsClients[conn].WriteMutex.Lock() conn.WriteMessage(1, jsonData) + wsClients[conn].WriteMutex.Unlock() } wsClientsMutex.Unlock() } @@ -496,7 +503,9 @@ func onPortListChange() { Type: "portListChange", ResponseData: gin.H{"inputs": portConfig.Input, "outputs": portConfig.Output}, }) + wsClients[conn].WriteMutex.Lock() conn.WriteMessage(1, jsonData) + wsClients[conn].WriteMutex.Unlock() } wsClientsMutex.Unlock() }