-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredistore.go
More file actions
210 lines (188 loc) · 5.1 KB
/
redistore.go
File metadata and controls
210 lines (188 loc) · 5.1 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package gsr
import (
"bytes"
"context"
"encoding/base32"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"github.com/go-redis/redis/v8"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"net/http"
"strings"
"time"
)
var (
defaultMaxAge = 60 * 20
sessionExpire = 86400 * 30
)
//Serializer
type Serializer interface {
Deserialize(d []byte, ss *sessions.Session) error
Serialize(ss *sessions.Session) ([]byte, error)
}
//JSONSerializer 使用json数据格式人为可读
type JSONSerializer struct{}
func (s JSONSerializer) Serialize(ss *sessions.Session) ([]byte, error) {
m := make(map[string]interface{}, len(ss.Values))
for k, v := range ss.Values {
ks, ok := k.(string)
if !ok {
err := fmt.Errorf("Non-string key value, cannot serialize session to JSON: %v\n", k)
return nil, err
}
m[ks] = v
}
return json.Marshal(m)
}
func (s JSONSerializer) Deserialize(d []byte, ss *sessions.Session) error {
m := make(map[string]interface{})
err := json.Unmarshal(d, &m)
if err != nil {
return err
}
for k, v := range m {
ss.Values[k] = v
}
return nil
}
//GobSerializer go 特有编码方式,此种编码数据不能与其他语言通信
type GobSerializer struct{}
func (s GobSerializer) Serialize(ss *sessions.Session) ([]byte, error) {
buf := new(bytes.Buffer)
encode := gob.NewEncoder(buf)
err := encode.Encode(ss.Values)
if err == nil {
return buf.Bytes(), nil
}
return nil, err
}
func (s GobSerializer) Deserialize(d []byte, ss *sessions.Session) error {
decoder := gob.NewDecoder(bytes.NewBuffer(d))
return decoder.Decode(&ss.Values)
}
type RedisStore struct {
client *redis.Client
Codecs []securecookie.Codec
Options *sessions.Options
DefaultMaxAge int
maxLength int
keyPrefix string
serializer Serializer
}
func (s *RedisStore) SetMaxLength(l int) {
if l >= 0 {
s.maxLength = l
}
}
func (s *RedisStore) SetKeyPrefix(p string) {
s.keyPrefix = p
}
func (s *RedisStore) SetSerializer(ss Serializer) {
s.serializer = ss
}
func (s *RedisStore) SetMaxAge(v int) {
var c *securecookie.SecureCookie
var ok bool
s.Options.MaxAge = v
for i := range s.Codecs {
if c, ok = s.Codecs[i].(*securecookie.SecureCookie); ok {
c.MaxAge(v)
} else {
fmt.Printf("Can't change MaxAge on codec %v\n", s.Codecs[i])
}
}
}
func NewRedisStoreWithDB(ctx context.Context, client *redis.Client, keyPairs ...[]byte) (*RedisStore, error) {
rs := &RedisStore{
client: client,
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Options: &sessions.Options{
Path: "/",
MaxAge: sessionExpire,
},
DefaultMaxAge: defaultMaxAge,
maxLength: 4096,
keyPrefix: "gosession_",
serializer: GobSerializer{}, // JSONSerializer{} 使用json数据格式人为可读
}
return rs, rs.client.Ping(ctx).Err()
}
func (s *RedisStore) Close() error {
return s.client.Close()
}
func (s *RedisStore) Get(r *http.Request, name string) (*sessions.Session, error) {
return sessions.GetRegistry(r).Get(s, name)
}
func (s *RedisStore) New(r *http.Request, name string) (*sessions.Session, error) {
var (
err error
ok bool
)
session := sessions.NewSession(s, name)
options := *s.Options
session.Options = &options
session.IsNew = true
if c, errCookie := r.Cookie(name); errCookie == nil {
err = securecookie.DecodeMulti(name, c.Value, &session.ID, s.Codecs...)
if err == nil {
ok, err = s.load(r.Context(), session)
session.IsNew = !(err == nil && ok)
}
}
return session, err
}
func (s *RedisStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
if session.Options.MaxAge <= 0 {
if err := s.delete(r.Context(), session); err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options))
} else {
if session.ID == "" {
session.ID = strings.TrimRight(base32.StdEncoding.EncodeToString(securecookie.GenerateRandomKey(32)), "")
}
if err := s.save(r.Context(), session); err != nil {
return err
}
encode, err := securecookie.EncodeMulti(session.Name(), session.ID, s.Codecs...)
if err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), encode, session.Options))
}
return nil
}
func (s *RedisStore) save(ctx context.Context, session *sessions.Session) error {
b, err := s.serializer.Serialize(session)
if err != nil {
return err
}
if s.maxLength != 0 && len(b) > s.maxLength {
return errors.New("SessionStore the value to store is too big, you need set more maxLength")
}
age := session.Options.MaxAge
if age == 0 {
age = s.DefaultMaxAge
}
err = s.client.Set(ctx, s.keyPrefix+session.ID, b, time.Duration(age)*time.Second).Err()
return err
}
func (s *RedisStore) load(ctx context.Context, session *sessions.Session) (bool, error) {
b, err := s.client.Get(ctx, s.keyPrefix+session.ID).Bytes()
switch {
case err == redis.Nil:
return false, err
case err != nil:
return false, err
case len(b) == 0:
return false, err
default:
return true, s.serializer.Deserialize(b, session)
}
}
func (s *RedisStore) delete(ctx context.Context, session *sessions.Session) error {
return s.client.Del(ctx, s.keyPrefix+session.ID).Err()
}