From cb9e30948c8f1dd099f5168218d110765989992e Mon Sep 17 00:00:00 2001 From: "Gerasimos (Makis) Maropoulos" Date: Sat, 3 Feb 2018 18:53:39 +0200 Subject: [PATCH] add websocket/Connection#IsJoined as requested at https://github.com/kataras/iris/issues/895 --- websocket/connection.go | 7 +++++++ websocket/server.go | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/websocket/connection.go b/websocket/connection.go index ce887e95a6..a38decd715 100644 --- a/websocket/connection.go +++ b/websocket/connection.go @@ -174,6 +174,9 @@ type ( On(string, MessageFunc) // Join registers this connection to a room, if it doesn't exist then it creates a new. One room can have one or more connections. One connection can be joined to many rooms. All connections are joined to a room specified by their `ID` automatically. Join(string) + // IsJoined returns true when this connection is joined to the room, otherwise false. + // It Takes the room name as its input parameter. + IsJoined(roomName string) bool // Leave removes this connection entry from a room // Returns true if the connection has actually left from the particular room. Leave(string) bool @@ -506,6 +509,10 @@ func (c *connection) Join(roomName string) { c.server.Join(roomName, c.id) } +func (c *connection) IsJoined(roomName string) bool { + return c.server.IsJoined(roomName, c.id) +} + func (c *connection) Leave(roomName string) bool { return c.server.Leave(roomName, c.id) } diff --git a/websocket/server.go b/websocket/server.go index aec5de3332..a08b3e1a44 100644 --- a/websocket/server.go +++ b/websocket/server.go @@ -256,6 +256,28 @@ func (s *Server) join(roomName string, connID string) { s.rooms[roomName] = append(s.rooms[roomName], connID) } +// IsJoined reports if a specific room has a specific connection into its values. +// First parameter is the room name, second is the connection's id. +// +// It returns true when the "connID" is joined to the "roomName". +func (s *Server) IsJoined(roomName string, connID string) bool { + s.mu.RLock() + room := s.rooms[roomName] + s.mu.RUnlock() + + if room == nil { + return false + } + + for _, connid := range room { + if connID == connid { + return true + } + } + + return false +} + // LeaveAll kicks out a connection from ALL of its joined rooms func (s *Server) LeaveAll(connID string) { s.mu.Lock()