/
sessionList.go
77 lines (68 loc) · 1.53 KB
/
sessionList.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package session
import (
"sync"
"github.com/gorilla/websocket"
)
type SessionList struct {
sync.RWMutex
mapOnlineList map[string]*Session //key is SessionId
}
func NewSessionList() *SessionList {
return &SessionList{
mapOnlineList: make(map[string]*Session),
}
}
func (sl *SessionList) NewSession(wsConn *websocket.Conn) (session *Session, err error) {
session, err = newSession(wsConn)
if err == nil {
sl.addOnlineSession(session)
}
return session, err
}
func (sl *SessionList) CloseSession(session *Session) {
if session == nil {
return
}
sl.removeSession(session)
session.close()
}
func (sl *SessionList) addOnlineSession(session *Session) {
if session.GetSessionId() == "" {
return
}
sl.Lock()
defer sl.Unlock()
sl.mapOnlineList[session.GetSessionId()] = session
}
func (sl *SessionList) removeSession(iSession *Session) (err error) {
return sl.removeSessionById(iSession.GetSessionId())
}
func (sl *SessionList) removeSessionById(sSessionId string) (err error) {
if sSessionId == "" {
return err
}
sl.Lock()
defer sl.Unlock()
delete(sl.mapOnlineList, sSessionId)
return nil
}
func (sl *SessionList) GetSessionById(sSessionId string) *Session {
sl.RLock()
defer sl.RUnlock()
if session, ok := sl.mapOnlineList[sSessionId]; ok {
return session
}
return nil
}
func (sl *SessionList) GetSessionCount() int {
sl.RLock()
defer sl.RUnlock()
return len(sl.mapOnlineList)
}
func (sl *SessionList) ForEachSession(visit func(*Session)) {
sl.RLock()
defer sl.RUnlock()
for _, v := range sl.mapOnlineList {
visit(v)
}
}