-
Notifications
You must be signed in to change notification settings - Fork 1
/
session.go
108 lines (90 loc) · 1.91 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
package session
import (
"log"
"net/http"
"sync"
"github.com/gorilla/sessions"
// "gopkg.in/boj/redistore.v1"
)
type (
Options struct {
Name string
SecreKey string
MaxAge int
}
Session struct {
Store *sessions.CookieStore
Name string
}
)
var (
store *sessions.CookieStore
once sync.Once
)
func GetSession() *sessions.CookieStore {
once.Do(func() {
store = NewSession(&Options{
Name: "session_id",
SecreKey: "secret-key",
MaxAge: 60 * 60 * 30,
}).Store
})
return store
}
func NewSession(o *Options) *Session {
store := sessions.NewCookieStore([]byte(o.SecreKey))
// store, err := NewRediStore(10, "tcp", ":6379", "", []byte("secret-key"))
// store.KeyPrefix("session_")
store.Options = &sessions.Options{
Path: "/",
MaxAge: o.MaxAge,
HttpOnly: true,
}
return &Session{
Store: store,
Name: o.Name,
}
}
func (s *Session) Session(r *http.Request) (session *sessions.Session) {
session, err := s.Store.Get(r, s.Name)
if err != nil {
log.Fatalf("session err : %v", err)
}
return
}
func (s *Session) Get(r *http.Request, key string) (val interface{}, err error) {
session, err := s.Store.Get(r, s.Name)
if err != nil {
return
}
val = session.Values[key]
return
}
func (s *Session) Set(w http.ResponseWriter, r *http.Request, key interface{}, val interface{}) (err error) {
session, err := s.Store.Get(r, s.Name)
if err != nil {
return
}
session.Values[key] = val
err = session.Save(r, w)
return
}
func (s *Session) Delete(w http.ResponseWriter, r *http.Request, key interface{}) (err error) {
session, err := s.Store.Get(r, s.Name)
if err != nil {
return
}
delete(session.Values, key)
err = session.Save(r, w)
return
}
func (s *Session) Clear(w http.ResponseWriter, r *http.Request) (err error) {
session, err := s.Store.Get(r, s.Name)
if err != nil {
return
}
for key := range session.Values {
s.Delete(w, r, key)
}
return
}