feat: add thread safety to web socket list
This commit is contained in:
parent
4e639fb387
commit
6d2fca696e
@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/labstack/echo/v4"
|
||||
@ -14,12 +15,14 @@ type WebsocketHandler interface {
|
||||
}
|
||||
|
||||
type WebsocketServer struct {
|
||||
router *echo.Echo
|
||||
sockets map[string]*websocket.Conn
|
||||
handlers []WebsocketHandler
|
||||
router *echo.Echo
|
||||
sockets map[string]*websocket.Conn
|
||||
handlers []WebsocketHandler
|
||||
socketsMutex *sync.Mutex
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) Initialize(authenticator *Authenticator) {
|
||||
s.socketsMutex = &sync.Mutex{}
|
||||
s.sockets = make(map[string]*websocket.Conn)
|
||||
s.router.Use(authenticator.Authenticate("/ws", []string{}))
|
||||
s.router.GET("/ws", s.handle)
|
||||
@ -29,13 +32,17 @@ func (s *WebsocketServer) handle(context echo.Context) error {
|
||||
authContext := context.(AuthContext)
|
||||
senderId := getAuthenticatedId(authContext)
|
||||
ws, err := upgrader.Upgrade(context.Response(), context.Request(), nil)
|
||||
s.socketsMutex.Lock()
|
||||
s.sockets[senderId] = ws
|
||||
s.socketsMutex.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
ws.Close()
|
||||
s.socketsMutex.Lock()
|
||||
delete(s.sockets, senderId)
|
||||
s.socketsMutex.Unlock()
|
||||
}()
|
||||
|
||||
for {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user