-
Notifications
You must be signed in to change notification settings - Fork 0
/
http-session.go
94 lines (78 loc) · 1.59 KB
/
http-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
package session
import (
"encoding/json"
"github.com/omecodes/errors"
"net/http"
"github.com/gorilla/sessions"
)
type Cookie struct {
http.Cookie
}
type WebSession struct {
store *sessions.CookieStore
httpSession *sessions.Session
r *http.Request
}
func GetWebSession(name string, r *http.Request) (*WebSession, error) {
s := new(WebSession)
storeValue := r.Context().Value(ctxCookieStore{})
if storeValue == nil {
return nil, errors.Internal("context missing cookies store")
}
s.store = storeValue.(*sessions.CookieStore)
s.r = r
s.httpSession, _ = s.store.Get(r, name)
return s, nil
}
func (s *WebSession) Put(key string, value interface{}) {
s.httpSession.Values[key] = value
}
func (s *WebSession) Get(key string) interface{} {
v, ok := s.httpSession.Values[key]
if !ok {
return nil
}
return v
}
func (s *WebSession) Delete(key string) {
delete(s.httpSession.Values, key)
}
func (s *WebSession) String(key string) string {
v, ok := s.httpSession.Values[key]
if !ok {
return ""
}
str, ok := v.(string)
if !ok {
return ""
}
return str
}
func (s *WebSession) Bool(key string) bool {
v, ok := s.httpSession.Values[key]
if !ok {
return ok
}
b, ok := v.(bool)
if !ok {
return false
}
return b
}
func (s *WebSession) Int64(key string) int64 {
v, ok := s.httpSession.Values[key]
if !ok {
return 0
}
b, ok := v.(int64)
if !ok {
return 0
}
return b
}
func (s *WebSession) Save(w http.ResponseWriter) error {
return s.httpSession.Save(s.r, w)
}
func (s *WebSession) Encoded() ([]byte, error) {
return json.Marshal(s.httpSession.Values)
}