/
session.go
110 lines (89 loc) · 2.28 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
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
package session
import (
"errors"
"log"
"github.com/chances/party-server/cache"
)
const (
sessionDefaultKey = "github.com/chances/party-server/session"
)
// Session is a hella simple string value session store for party-server
type Session struct {
name string
ID string
flashes map[string]string
store cache.Store
}
func (s *Session) saveFlashes() {
if s.flashes == nil {
return
}
err := s.store.Set(s.ID+":flashes", cache.Forever(s.flashes))
if err != nil {
log.Println(s.flashes)
log.Fatal("cp flash:", err)
}
}
// Get returns the session value associated to the given key.
func (s *Session) Get(key string) (string, error) {
entry, err := s.store.Get(s.ID + ":" + key)
if err != nil {
return "", err
}
value := entry.Value.(string)
return value, nil
}
// Set sets the session value associated to the given key.
func (s *Session) Set(key string, value string) error {
return s.store.Set(s.ID+":"+key, cache.Forever(value))
}
// Flash a keyed value to session flash storage
func (s *Session) Flash(key string, value string) {
s.flashes[key] = value
s.saveFlashes()
}
// Flashes retrieves values from session flash storage
func (s *Session) Flashes(key ...string) ([]string, error) {
numKeys := len(key)
if numKeys == 0 {
flashes := s.flashes
val := make([]string, len(flashes))
idx := 0
for _, value := range flashes {
val[idx] = value
idx++
}
s.flashes = make(map[string]string)
s.saveFlashes()
return val, nil
} else if numKeys == 1 {
if val, ok := s.flashes[key[0]]; ok {
valResult := make([]string, 1)
valResult[0] = val
delete(s.flashes, key[0])
s.saveFlashes()
return valResult, nil
}
return make([]string, 0), nil
}
return nil, errors.New("Flashes accepts only zero or one keys")
}
// Error retrieves an error from session flash storage
func (s *Session) Error() (string, error) {
flashErrors, err := s.Flashes("error")
if err != nil {
return "", err
}
if len(flashErrors) > 0 {
return flashErrors[0], nil
}
return "", nil
}
// Delete removes the session value associated with the given key
func (s *Session) Delete(key string) error {
return s.store.Delete(s.ID + ":" + key)
}
// Logout effectively ends a session by deleting user-land keys
func (s *Session) Logout() error {
return s.Delete("USER")
}