-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.go
More file actions
81 lines (67 loc) · 1.48 KB
/
session.go
File metadata and controls
81 lines (67 loc) · 1.48 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 middleware
import (
"net/http"
"sync"
"time"
)
var globalSession = make(map[string]*Session)
var globalSessionLock sync.RWMutex
var globalSessionExpireSeconds = 6000.00
// 基于内存session
type Session struct {
sync.RWMutex
id string
data map[string]interface{}
lastTouchTime time.Time
}
func newSession(context Context) *Session {
id := Guid()
s := Session{
id: id,
data: make(map[string]interface{}),
lastTouchTime: time.Now(),
}
context.SetCookie(&http.Cookie{
Name: "sessionId",
Value: id,
HttpOnly: true,
})
globalSessionLock.Lock()
globalSession[id] = &s
globalSessionLock.Unlock()
return &s
}
func getSession(context Context) *Session {
s, ok := globalSession[context.GetCookie("sessionId")]
if ok {
return s
}
return newSession(context)
}
func (t *Session) Set(key string, val interface{}) {
t.data[key] = val
}
func (t *Session) Get(key string) interface{} {
return t.data[key]
}
func (t *Session) Id() string {
return t.id
}
func init() {
// session过期
// Schedule("session-expire", 30*60, func() {
// for k, v := range globalSession {
// v.Lock()
// if time.Now().Sub(v.lastTouchTime).Seconds() > globalSessionExpireSeconds {
// delete(globalSession, k)
// }
// v.Unlock()
// }
// })
}
func (c *Context) SessionSet(key string, value interface{}) {
getSession(*c).Set(key, value)
}
func (c *Context) SessionGet(key string) interface{} {
return getSession(*c).Get(key)
}