diff --git a/database/socket/database.go b/database/socket/database.go index 3a0f9fd..c5e6083 100644 --- a/database/socket/database.go +++ b/database/socket/database.go @@ -8,6 +8,7 @@ package socket import ( "log" "net" + "sync" "time" "github.com/FreifunkBremen/yanic/database" @@ -16,8 +17,9 @@ import ( type Connection struct { database.Connection - listener net.Listener - clients map[net.Addr]net.Conn + listener net.Listener + clients map[net.Addr]net.Conn + clientMux sync.Mutex } func init() { @@ -56,8 +58,10 @@ func (conn *Connection) PruneNodes(deleteAfter time.Duration) { } func (conn *Connection) Close() { + conn.clientMux.Lock() for _, c := range conn.clients { c.Close() } + conn.clientMux.Unlock() conn.listener.Close() } diff --git a/database/socket/internal.go b/database/socket/internal.go index 662dc8d..311ce2d 100644 --- a/database/socket/internal.go +++ b/database/socket/internal.go @@ -11,18 +11,21 @@ type EventMessage struct { Body interface{} `json:"body,omitempty"` } -func (config *Connection) handleSocketConnection(ln net.Listener) { +func (conn *Connection) handleSocketConnection(ln net.Listener) { for { c, err := ln.Accept() if err != nil { log.Println("[socket-database] error during connection of a client", err) continue } - config.clients[c.RemoteAddr()] = c + conn.clientMux.Lock() + conn.clients[c.RemoteAddr()] = c + conn.clientMux.Unlock() } } func (conn *Connection) sendJSON(msg EventMessage) { + conn.clientMux.Lock() for addr, c := range conn.clients { d := json.NewEncoder(c) @@ -33,4 +36,5 @@ func (conn *Connection) sendJSON(msg EventMessage) { delete(conn.clients, addr) } } + conn.clientMux.Unlock() }