-
Notifications
You must be signed in to change notification settings - Fork 3
/
session.go
executable file
·123 lines (104 loc) · 2.12 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
111
112
113
114
115
116
117
118
119
120
121
122
123
/*
gow session
sam
2021/6/7
r:=gow.New()
r.Use(Session())
*/
package gow
import (
"fmt"
"github.com/zituocn/gow/session"
"strconv"
)
var (
cookieName = "gow_session_id"
sessionManager *session.Manager
sessionID string
)
// InitSession init gow session
//
// before using session,please call this function first
func InitSession() {
sessionManager = session.NewSessionManager(cookieName, 3600)
}
// Session middleware
//
// r := gow.Default()
// r.Use(gow.Session())
func Session() HandlerFunc {
return func(c *Context) {
if sessionManager == nil {
panic("Please call gow.InitSession() first")
}
sessionID = sessionManager.Start(c.Writer, c.Request)
sessionManager.Extension(c.Writer, c.Request)
c.Next()
}
}
// SetSession set session
func (c *Context) SetSession(key string, v interface{}) {
setSession(key, v)
}
// GetSession return interface
func (c *Context) GetSession(key string) interface{} {
return getSession(key)
}
// SessionString return string
func (c *Context) SessionString(key string) string {
ret := c.GetSession(key)
v, ok := ret.(string)
if ok {
return v
}
return ""
}
// SessionInt return int
//
// default 0
func (c *Context) SessionInt(key string) int {
v := c.SessionInt64(key)
return int(v)
}
// SessionInt64 return int64
//
// default 0
func (c *Context) SessionInt64(key string) int64 {
ret := c.GetSession(key)
v, err := strconv.ParseInt(fmt.Sprintf("%v", ret), 10, 64)
if err != nil {
return 0
}
return v
}
// SessionBool return bool
//
// default false
func (c *Context) SessionBool(key string) bool {
ret := c.GetSession(key)
v, ok := ret.(bool)
if ok {
return v
}
return false
}
// DeleteSession delete session key
func (c *Context) DeleteSession(key string) {
deleteSession(key)
}
// getSession getSession
func getSession(key interface{}) interface{} {
v, ok := sessionManager.Get(sessionID, key)
if ok {
return v
}
return nil
}
// setSession setSession
func setSession(key, value interface{}) {
sessionManager.Set(sessionID, key, value)
}
// deleteSession deleteSession
func deleteSession(key interface{}) {
sessionManager.Delete(sessionID, key)
}