-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
81 lines (67 loc) · 1.72 KB
/
session.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
package gohttp
import (
"crypto/rand"
"encoding/base64"
"io"
"time"
)
type CacheProvider interface {
Exists(key string) bool
HExists(key, field string) bool
HGet(key, field string) interface{}
HSet(key, field string, value interface{}, expiration time.Duration)
HDelete(key, field string) bool
}
type SessionManager interface {
GetSession(sessionId string) Session
CreateSession() (string, Session)
}
func NewSessionManager(cacheProvider CacheProvider) SessionManager {
return &sessionManager{
cacheProvider,
}
}
type sessionManager struct {
cacheProvider CacheProvider
}
func (sm *sessionManager) GetSession(sessionId string) Session {
if sm.cacheProvider.Exists(sessionId) {
return newSession(sessionId, sm.cacheProvider)
} else {
return nil
}
}
func (sm *sessionManager) CreateSession() (string, Session) {
sessionId := generateSessionId()
return sessionId, newSession(sessionId, sm.cacheProvider)
}
func generateSessionId() string {
b := make([]byte, 32)
_, _ = io.ReadFull(rand.Reader, b)
return base64.URLEncoding.EncodeToString(b)
}
type session struct {
sessionId string
provider CacheProvider
}
func newSession(sessionId string, provider CacheProvider) Session {
return &session{sessionId, provider}
}
func (s *session) Exists(key string) bool {
return s.provider.HExists(s.sessionId, key)
}
func (s *session) Get(key string) interface{} {
return s.provider.HGet(s.sessionId, key)
}
func (s *session) Set(key string, value interface{}, expiration time.Duration) {
s.provider.HSet(s.sessionId, key, value, expiration)
}
func (s *session) Delete(key string) bool {
if !s.provider.HExists(s.sessionId, key) {
return true
}
if s.provider.HDelete(s.sessionId, key) {
return true
}
return false
}