-
Notifications
You must be signed in to change notification settings - Fork 0
/
session_manager.go
67 lines (51 loc) · 1.21 KB
/
session_manager.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
package remotedialer
import (
"fmt"
"math/rand"
"sync"
"github.com/gorilla/websocket"
)
type sessionManager struct {
sync.Mutex
clients map[string][]*session
}
func newSessionManager() *sessionManager {
return &sessionManager{
clients: map[string][]*session{},
}
}
func (sm *sessionManager) getByClient(clientKey string) (*session, error) {
sm.Lock()
defer sm.Unlock()
sessions := sm.clients[clientKey]
if len(sessions) > 0 {
return sessions[0], nil
}
return nil, fmt.Errorf("failed to find session for client %s", clientKey)
}
func (sm *sessionManager) add(clientKey string, conn *websocket.Conn) *session {
sessionKey := rand.Int63()
session := newSession(sessionKey, clientKey, conn)
session.sessionKey = sessionKey
sm.Lock()
defer sm.Unlock()
sm.clients[clientKey] = append(sm.clients[clientKey], session)
return session
}
func (sm *sessionManager) remove(s *session) {
sm.Lock()
defer sm.Unlock()
var newSessions []*session
for _, v := range sm.clients[s.clientKey] {
if v.sessionKey == s.sessionKey {
continue
}
newSessions = append(newSessions, v)
}
if len(newSessions) == 0 {
delete(sm.clients, s.clientKey)
} else {
sm.clients[s.clientKey] = newSessions
}
s.Close()
}