-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsession.go
More file actions
116 lines (102 loc) · 2.83 KB
/
session.go
File metadata and controls
116 lines (102 loc) · 2.83 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
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
111
112
113
114
115
116
package ink
import (
"fmt"
"net/http"
)
// session store interface
var sessionStore SessionStore
type SessionStore interface {
Create(sessionId string)
Get(sessionId string) map[string]interface{}
}
type defaultSessionStore map[string]map[string]interface{}
func (store *defaultSessionStore) Create(sessionId string) {
(*store)[sessionId] = make(map[string]interface{})
}
func (store *defaultSessionStore) Get(sessionId string) map[string]interface{} {
item, ok := (*store)[sessionId]
if ok {
return item
}
return nil
}
// cookie manage interface
var cookieManage *CookieManage
type CookieManage struct {
Set func(ctx *Context, value string)
Get func(ctx *Context) string
}
// default session name
const sessionName = "session"
/* public method */
func (ctx *Context) SessionGet(key string) interface{} {
if sessionStore != nil {
sessionId := cookieManage.Get(ctx)
if len(sessionId) != 0 {
sessionItem := sessionStore.Get(sessionId)
if sessionItem != nil {
value, ok := sessionItem[key]
if ok {
return value
}
}
}
}
return nil
}
func (ctx *Context) SessionSet(key string, value interface{}) {
sessionId := cookieManage.Get(ctx)
if len(sessionId) != 0 {
if sessionStore != nil {
sessionItem := sessionStore.Get(sessionId)
if sessionItem != nil {
sessionItem[key] = value
}
}
}
}
func Session(store SessionStore, cm *CookieManage) func(ctx *Context) {
if store == nil {
newStore := make(defaultSessionStore)
sessionStore = SessionStore(&newStore)
} else {
sessionStore = store
}
if cm == nil {
cookieManage = new(CookieManage)
cookieManage.Get = func(ctx *Context) string {
cookie, err := ctx.Req.Cookie(sessionName)
if err != nil {
return ""
}
return cookie.Value
}
cookieManage.Set = func(ctx *Context, value string) {
http.SetCookie(ctx.Res, &http.Cookie {
Name: sessionName,
Value: value,
})
}
} else {
cookieManage = cm
}
createSession := func(ctx *Context) string {
sessionId := GUID()
sessionStore.Create(sessionId)
cookieManage.Set(ctx, sessionId)
return sessionId
}
return func(ctx *Context) {
sessionId := cookieManage.Get(ctx)
if len(sessionId) != 0 {
fmt.Println("HAVE TOKEN")
sessionItem := sessionStore.Get(sessionId)
if sessionItem == nil {
createSession(ctx)
}
} else {
fmt.Println("NO TOKEN")
createSession(ctx)
}
}
}