forked from hoisie/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
74 lines (58 loc) · 1.76 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
package web
import (
"github.com/sipin/web/randbo"
)
var SessionKey string = "ZQSESSID"
var sessionIDLen int = 36
type ISessionStorage interface {
SetSession(sessionID string, key string, data []byte)
GetSession(sessionID string, key string) []byte
ClearSession(sessionID string, key string)
}
func newSessionID() string {
return randbo.GenString(sessionIDLen / 2)
}
func (ctx *Context) SetSession(key string, data []byte) {
ctx.Server.SessionStorage.SetSession(ctx.GetSessionID(), key, data)
}
func (ctx *Context) GetSession(key string) []byte {
return ctx.Server.SessionStorage.GetSession(ctx.GetSessionID(), key)
}
func (ctx *Context) ClearSession(key string) {
ctx.Server.SessionStorage.ClearSession(ctx.GetSessionID(), key)
}
func (ctx *Context) AbandonSession() {
ctx.RemoveCookie(SessionKey)
return
}
func (ctx *Context) SetNewSessionID() (sessionID string) {
sessionID = newSessionID()
ctx.SetCookie(NewSessionCookie(SessionKey, sessionID))
return
}
// SetCookie adds a cookie header to the response.
func (ctx *Context) GetSessionID() (sessionID string) {
cookie, _ := ctx.Request.Cookie(SessionKey)
if cookie == nil || len(cookie.Value) != sessionIDLen {
return ctx.SetNewSessionID()
}
return cookie.Value
}
// Simple session storage using memory, handy for development
// **NEVER** use it in production!!!
type memoryStore struct {
data map[string][]byte
}
var MemoryStore = &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)
}