-
Notifications
You must be signed in to change notification settings - Fork 6
/
memory.go
114 lines (96 loc) · 2.16 KB
/
memory.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package ginsession
import (
"fmt"
uuid "github.com/satori/go.uuid"
"sync"
)
// memory-based session serve
// memSession session store in memory
type memSession struct {
id string
data map[string]interface{}
expired int
rwLock sync.RWMutex
}
// NewMemSession constructor
func NewMemSession(id string) *memSession {
return &memSession{
id: id,
data: make(map[string]interface{}, 8),
}
}
func (m *memSession) ID() string {
return m.id
}
func (m *memSession) Load()(err error) {
return
}
func (m *memSession) Get(key string) (value interface{}, err error) {
m.rwLock.RLock()
defer m.rwLock.RUnlock()
value, ok := m.data[key]
if !ok {
err = fmt.Errorf("invalid Key")
return
}
return
}
func (m *memSession) Set(key string, value interface{}) {
m.rwLock.Lock()
defer m.rwLock.Unlock()
m.data[key] = value
}
func (m *memSession) Del(key string) {
m.rwLock.Lock()
defer m.rwLock.Unlock()
delete(m.data, key)
}
// Save save session data to store
func (m *memSession) Save() {
return
}
// SetExpired set expired time
func (m *memSession) SetExpired(expired int) {
m.expired = expired
}
// MemSessionMgr a memory-based manager
type MemSessionMgr struct {
session map[string]Session
rwLock sync.RWMutex
}
// NewMemSessionMgr constructor
func NewMemSessionMgr() *MemSessionMgr {
return &MemSessionMgr{
session: make(map[string]Session, 1024),
}
}
// Init init...
func (m *MemSessionMgr) Init(addr string, options ...string) (err error) {
return
}
// GetSession get the session by sessionID
func (m *MemSessionMgr) GetSession(sessionID string) (sd Session, err error) {
m.rwLock.RLock()
defer m.rwLock.RUnlock()
sd, ok := m.session[sessionID]
if !ok {
err = fmt.Errorf("invalid session id")
return
}
return
}
// CreateSession create a new session
func (m *MemSessionMgr) CreateSession() (sd Session) {
// 1. generate a sessionID
sessionID := uuid.NewV4().String()
// 2. create a new memory-based session
sd = NewMemSession(sessionID)
m.session[sd.ID()] = sd
return
}
// Clear delete the request session in sessionMgr
func (m *MemSessionMgr)Clear(sessionID string){
m.rwLock.Lock()
defer m.rwLock.Unlock()
delete(m.session, sessionID)
}