🚑 Fix concurent writes in wsClients map

This commit is contained in:
2024-10-29 01:02:18 +01:00
parent 9c9f7798ab
commit 26720fa35e

12
api.go
View File

@ -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()
}