-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsession.go
More file actions
81 lines (65 loc) · 1.42 KB
/
session.go
File metadata and controls
81 lines (65 loc) · 1.42 KB
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 session
import (
"errors"
"time"
"crypto/rand"
)
type Session string
var (
sessions = make(map[string]map[string]interface{})
sessionTimeout = time.Hour //default expire session after 1 hour
)
func New() Session {
return NewTimeout(sessionTimeout)
}
func NewTimeout(timeout time.Duration) Session {
sid, err := generateSessionId()
if err != nil {
panic(err)
}
sessions[sid] = make(map[string]interface{})
t := time.NewTimer(timeout)
go startSession(t.C, sid)
return Session(sid)
}
func SessionFromId(sid string) Session {
return Session(sid)
}
func (s Session) RemoveSession() {
delete(sessions, string(s))
}
func (s Session) Exists() bool {
_, ok := sessions[string(s)]
return ok
}
func (s Session) Put(name string, value interface{}) error {
sobj, ok := sessions[string(s)]
if !ok {
return errors.New("Session does not exist.")
}
sobj[name] = value
return nil
}
func (s Session) Get(name string) (interface{}, error) {
sobj, ok := sessions[string(s)]
if !ok {
return nil, errors.New("Session does not exist.")
}
var v interface{}
v, ok = sobj[name]
if !ok {
return nil, errors.New("No such key.")
}
return v, nil
}
func startSession(c <-chan time.Time, sid string) {
<-c
delete(sessions, sid)
}
func generateSessionId() (string, error) {
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return string(bytes), nil
}