This repository has been archived by the owner on Jan 4, 2018. It is now read-only.
forked from sipin/xingyun
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsession_memory_store.go
74 lines (62 loc) · 1.75 KB
/
session_memory_store.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
package xingyun
import (
"time"
"github.com/xiaoenai/gomemcache/memcache"
)
// Simple session storage using memory, handy for development
// **NEVER** use it in production!!!
type memoryStore struct {
data map[string][]byte
}
func NewMemoryStore() *memoryStore {
return &memoryStore{
data: make(map[string][]byte),
}
}
func (ms *memoryStore) SetSession(sessionID string, key string, data []byte) {
ms.data[sessionID+key] = data
}
func (ms *memoryStore) GetSession(sessionID string, key string) []byte {
data, _ := ms.data[sessionID+key]
return data
}
func (ms *memoryStore) ClearSession(sessionID string, key string) {
delete(ms.data, sessionID+key)
}
type memcacheStore struct {
mc *memcache.Client
logger Logger
server *Server
}
func NewMemcacheStore(addr string, logger Logger, server *Server) *memcacheStore {
mc := memcache.New(addr)
mc.UseGet = true
return &memcacheStore{
mc: mc,
logger: logger,
server: server,
}
}
func (ms *memcacheStore) SetSession(sessionID string, key string, data []byte) {
_timeout := ms.server.Config.SessionTimeout * int32(time.Minute.Seconds())
err := ms.mc.Set(&memcache.Item{Key: ms.server.name() + ":" + sessionID + ":" + key, Value: data, Expiration: _timeout})
if err != nil {
ms.logger.Errorf("SetSession %s", err)
}
}
func (ms *memcacheStore) GetSession(sessionID string, key string) []byte {
item, err := ms.mc.Get(ms.server.name() + ":" + sessionID + ":" + key)
if err != nil {
if err != memcache.ErrCacheMiss {
ms.logger.Errorf("GetSession %s", err)
}
return nil
}
return item.Value
}
func (ms *memcacheStore) ClearSession(sessionID string, key string) {
err := ms.mc.Delete(ms.server.name() + ":" + sessionID + ":" + key)
if err != nil {
ms.logger.Errorf("ClearSession %s", err)
}
}