From 16f318d67ae143af28042d70e14bbc621e352011 Mon Sep 17 00:00:00 2001 From: nick Date: Mon, 29 Jul 2024 19:16:46 +0900 Subject: [PATCH] feat: quick return if condition not met --- node/pkg/dal/api/hub.go | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/node/pkg/dal/api/hub.go b/node/pkg/dal/api/hub.go index e585c2e24..d74135653 100644 --- a/node/pkg/dal/api/hub.go +++ b/node/pkg/dal/api/hub.go @@ -54,30 +54,40 @@ func (c *Hub) handleClientRegistration() { } func (c *Hub) addClient(conn *websocket.Conn) { - c.mu.Lock() - defer c.mu.Unlock() + c.mu.RLock() if _, ok := c.clients[conn]; ok { + c.mu.RUnlock() return } + c.mu.RUnlock() + + c.mu.Lock() + defer c.mu.Unlock() + c.clients[conn] = make(map[string]bool) } func (c *Hub) removeClient(conn *websocket.Conn) { + c.mu.RLock() + if _, ok := c.clients[conn]; !ok { + c.mu.RUnlock() + return + } + c.mu.RUnlock() + c.mu.Lock() defer c.mu.Unlock() - if _, ok := c.clients[conn]; ok { - for symbol := range c.clients[conn] { - delete(c.clients[conn], symbol) - } - delete(c.clients, conn) + + for symbol := range c.clients[conn] { + delete(c.clients[conn], symbol) } - if err := conn.WriteControl( + delete(c.clients, conn) + + _ = conn.WriteControl( websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second), - ); err != nil { - log.Error().Err(err).Msg("failed to send close message") - } + ) conn.Close() }