forked from googollee/go-engine.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.go
63 lines (53 loc) · 1.19 KB
/
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
package engineio
import (
"strconv"
"sync"
"sync/atomic"
)
// SessionIDGenerator generates new session id. Default behavior is simple
// increasing number.
// If you need custom session id, for example using local ip as perfix, you can
// implement SessionIDGenerator and save in Configure. Engine.io will use custom
// one to generate new session id.
type SessionIDGenerator interface {
NewID() string
}
type defaultIDGenerator struct {
nextID uint64
}
func (g *defaultIDGenerator) NewID() string {
id := atomic.AddUint64(&g.nextID, 1)
return strconv.FormatUint(id, 36)
}
type manager struct {
SessionIDGenerator
s map[string]*session
locker sync.RWMutex
}
func newManager(g SessionIDGenerator) *manager {
if g == nil {
g = &defaultIDGenerator{}
}
return &manager{
SessionIDGenerator: g,
s: make(map[string]*session),
}
}
func (m *manager) Add(s *session) {
m.locker.Lock()
defer m.locker.Unlock()
m.s[s.ID()] = s
}
func (m *manager) Get(sid string) *session {
m.locker.RLock()
defer m.locker.RUnlock()
return m.s[sid]
}
func (m *manager) Remove(sid string) {
m.locker.Lock()
defer m.locker.Unlock()
if _, ok := m.s[sid]; !ok {
return
}
delete(m.s, sid)
}