forked from alexedwards/scs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.go
632 lines (544 loc) · 16 KB
/
data.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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
package session
import (
"bytes"
"encoding/base64"
"encoding/gob"
"encoding/json"
"errors"
"net/http"
"sort"
"strconv"
"time"
)
// ErrTypeAssertionFailed is returned by operations on session data where the
// received value could not be type asserted or converted into the required type.
var ErrTypeAssertionFailed = errors.New("type assertion failed")
// GetString returns the string value for a given key from the session data. The
// zero value for a string ("") is returned if the key does not exist. An ErrTypeAssertionFailed
// error is returned if the value could not be type asserted or converted to a
// string.
func GetString(r *http.Request, key string) (string, error) {
v, exists, err := get(r, key)
if err != nil {
return "", err
}
if exists == false {
return "", nil
}
str, ok := v.(string)
if ok == false {
return "", ErrTypeAssertionFailed
}
return str, nil
}
// PutString adds a string value and corresponding key to the the session data.
// Any existing value for the key will be replaced.
func PutString(r *http.Request, key string, val string) error {
return put(r, key, val)
}
// PopString removes the string value for a given key from the session data
// and returns it. The zero value for a string ("") is returned if the key does
// not exist. An ErrTypeAssertionFailed error is returned if the value could not
// be type asserted to a string.
func PopString(r *http.Request, key string) (string, error) {
v, exists, err := pop(r, key)
if err != nil {
return "", err
}
if exists == false {
return "", nil
}
str, ok := v.(string)
if ok == false {
return "", ErrTypeAssertionFailed
}
return str, nil
}
// GetBool returns the bool value for a given key from the session data. The
// zero value for a bool (false) is returned if the key does not exist. An ErrTypeAssertionFailed
// error is returned if the value could not be type asserted to a bool.
func GetBool(r *http.Request, key string) (bool, error) {
v, exists, err := get(r, key)
if err != nil {
return false, err
}
if exists == false {
return false, nil
}
b, ok := v.(bool)
if ok == false {
return false, ErrTypeAssertionFailed
}
return b, nil
}
// PutBool adds a bool value and corresponding key to the session data. Any existing
// value for the key will be replaced.
func PutBool(r *http.Request, key string, val bool) error {
return put(r, key, val)
}
// PopBool removes the bool value for a given key from the session data and returns
// it. The zero value for a bool (false) is returned if the key does not exist.
// An ErrTypeAssertionFailed error is returned if the value could not be type
// asserted to a bool.
func PopBool(r *http.Request, key string) (bool, error) {
v, exists, err := pop(r, key)
if err != nil {
return false, err
}
if exists == false {
return false, nil
}
b, ok := v.(bool)
if ok == false {
return false, ErrTypeAssertionFailed
}
return b, nil
}
// GetInt returns the int value for a given key from the session data. The zero
// value for an int (0) is returned if the key does not exist. An ErrTypeAssertionFailed
// error is returned if the value could not be type asserted or converted to a int.
func GetInt(r *http.Request, key string) (int, error) {
v, exists, err := get(r, key)
if err != nil {
return 0, err
}
if exists == false {
return 0, nil
}
switch v := v.(type) {
case int:
return v, nil
case json.Number:
return strconv.Atoi(v.String())
}
return 0, ErrTypeAssertionFailed
}
// PutInt adds an int value and corresponding key to the session data. Any existing
// value for the key will be replaced.
func PutInt(r *http.Request, key string, val int) error {
return put(r, key, val)
}
// PopInt removes the int value for a given key from the session data and returns
// it. The zero value for an int (0) is returned if the key does not exist. An
// ErrTypeAssertionFailed error is returned if the value could not be type asserted
// or converted to a int.
func PopInt(r *http.Request, key string) (int, error) {
v, exists, err := pop(r, key)
if err != nil {
return 0, err
}
if exists == false {
return 0, nil
}
switch v := v.(type) {
case int:
return v, nil
case json.Number:
return strconv.Atoi(v.String())
}
return 0, ErrTypeAssertionFailed
}
//
// GetInt64 returns the int64 value for a given key from the session data. The
// zero value for an int (0) is returned if the key does not exist. An ErrTypeAssertionFailed
// error is returned if the value could not be type asserted or converted to a int64.
func GetInt64(r *http.Request, key string) (int64, error) {
v, exists, err := get(r, key)
if err != nil {
return 0, err
}
if exists == false {
return 0, nil
}
switch v := v.(type) {
case int64:
return v, nil
case json.Number:
return v.Int64()
}
return 0, ErrTypeAssertionFailed
}
// PutInt64 adds an int64 value and corresponding key to the session data. Any existing
// value for the key will be replaced.
func PutInt64(r *http.Request, key string, val int64) error {
return put(r, key, val)
}
// PopInt64 remvoes the int64 value for a given key from the session data
// and returns it. The zero value for an int (0) is returned if the key does not
// exist. An ErrTypeAssertionFailed error is returned if the value could not be
// type asserted or converted to a int64.
func PopInt64(r *http.Request, key string) (int64, error) {
v, exists, err := pop(r, key)
if err != nil {
return 0, err
}
if exists == false {
return 0, nil
}
switch v := v.(type) {
case int64:
return v, nil
case json.Number:
return v.Int64()
}
return 0, ErrTypeAssertionFailed
}
// GetFloat returns the float64 value for a given key from the session data. The
// zero value for an float (0) is returned if the key does not exist. An ErrTypeAssertionFailed
// error is returned if the value could not be type asserted or converted to a
// float64.
func GetFloat(r *http.Request, key string) (float64, error) {
v, exists, err := get(r, key)
if err != nil {
return 0, err
}
if exists == false {
return 0, nil
}
switch v := v.(type) {
case float64:
return v, nil
case json.Number:
return v.Float64()
}
return 0, ErrTypeAssertionFailed
}
// PutFloat adds an float64 value and corresponding key to the session data. Any
// existing value for the key will be replaced.
func PutFloat(r *http.Request, key string, val float64) error {
return put(r, key, val)
}
// PopFloat removes the float64 value for a given key from the session data
// and returns it. The zero value for an float (0) is returned if the key does
// not exist. An ErrTypeAssertionFailed error is returned if the value could not
// be type asserted or converted to a float64.
func PopFloat(r *http.Request, key string) (float64, error) {
v, exists, err := pop(r, key)
if err != nil {
return 0, err
}
if exists == false {
return 0, nil
}
switch v := v.(type) {
case float64:
return v, nil
case json.Number:
return v.Float64()
}
return 0, ErrTypeAssertionFailed
}
// GetTime returns the time.Time value for a given key from the session data. The
// zero value for a time.Time object is returned if the key does not exist (this
// can be checked for with the time.IsZero method). An ErrTypeAssertionFailed
// error is returned if the value could not be type asserted or converted to a
// time.Time.
func GetTime(r *http.Request, key string) (time.Time, error) {
v, exists, err := get(r, key)
if err != nil {
return time.Time{}, err
}
if exists == false {
return time.Time{}, nil
}
switch v := v.(type) {
case time.Time:
return v, nil
case string:
return time.Parse(time.RFC3339, v)
}
return time.Time{}, ErrTypeAssertionFailed
}
// PutTime adds an time.Time value and corresponding key to the session data. Any
// existing value for the key will be replaced.
func PutTime(r *http.Request, key string, val time.Time) error {
return put(r, key, val)
}
// PopTime removes the time.Time value for a given key from the session data
// and returns it. The zero value for a time.Time object is returned if the key
// does not exist (this can be checked for with the time.IsZero method). An ErrTypeAssertionFailed
// error is returned if the value could not be type asserted or converted to a
// time.Time.
func PopTime(r *http.Request, key string) (time.Time, error) {
v, exists, err := pop(r, key)
if err != nil {
return time.Time{}, err
}
if exists == false {
return time.Time{}, nil
}
switch v := v.(type) {
case time.Time:
return v, nil
case string:
return time.Parse(time.RFC3339, v)
}
return time.Time{}, ErrTypeAssertionFailed
}
// GetBytes returns the byte slice ([]byte) value for a given key from the session
// data. The zero value for a slice (nil) is returned if the key does not exist.
// An ErrTypeAssertionFailed error is returned if the value could not be type
// asserted or converted to []byte.
func GetBytes(r *http.Request, key string) ([]byte, error) {
v, exists, err := get(r, key)
if err != nil {
return nil, err
}
if exists == false {
return nil, nil
}
switch v := v.(type) {
case []byte:
return v, nil
case string:
return base64.StdEncoding.DecodeString(v)
}
return nil, ErrTypeAssertionFailed
}
// PutBytes adds a byte slice ([]byte) value and corresponding key to the the
// session data. Any existing value for the key will be replaced.
func PutBytes(r *http.Request, key string, val []byte) error {
if val == nil {
return errors.New("value must not be nil")
}
return put(r, key, val)
}
// PopBytes removes the byte slice ([]byte) value for a given key from the session
// data and returns it. The zero value for a slice (nil) is returned if the key
// does not exist. An ErrTypeAssertionFailed error is returned if the value could
// not be type asserted or converted to a []byte.
func PopBytes(r *http.Request, key string) ([]byte, error) {
v, exists, err := pop(r, key)
if err != nil {
return nil, err
}
if exists == false {
return nil, nil
}
switch v := v.(type) {
case []byte:
return v, nil
case string:
return base64.StdEncoding.DecodeString(v)
}
return nil, ErrTypeAssertionFailed
}
/*
GetObject reads the data for a given session key into an arbitrary object
(represented by the dst parameter). It should only be used to retrieve custom
data types that have been stored using PutObject. The object represented by dst
will remain unchanged if the key does not exist.
The dst parameter must be a pointer.
Usage:
// Note that the fields on the custom type are all exported.
type User struct {
Name string
Email string
}
func getHandler(w http.ResponseWriter, r *http.Request) {
// Register the type with the encoding/gob package. Usually this would be
// done in an init() function.
gob.Register(User{})
// Initialise a pointer to a new, empty, custom object.
user := &User{}
// Read the custom object data from the session into the pointer.
err := session.GetObject(r, "user", user)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
fmt.Fprintf(w, "Name: %s, Email: %s", user.Name, user.Email)
}
*/
func GetObject(r *http.Request, key string, dst interface{}) error {
b, err := GetBytes(r, key)
if err != nil {
return err
}
if b == nil {
return nil
}
return gobDecode(b, dst)
}
/*
PutObject adds an arbitrary object and corresponding key to the the session data.
Any existing value for the key will be replaced.
The val parameter must be a pointer to your object.
PutObject is typically used to store custom data types. It encodes the object
into a gob and then into a base64-encoded string which is persisted by the
storage engine. This makes PutObject (and the accompanying GetObject and PopObject
functions) comparatively expensive operations.
Because gob encoding is used, the fields on custom types must be exported in
order to be persisted correctly. Custom data types must also be registered with
gob.Register before PutObject is called (see https://golang.org/pkg/encoding/gob/#Register).
Usage:
type User struct {
Name string
Email string
}
func putHandler(w http.ResponseWriter, r *http.Request) {
// Register the type with the encoding/gob package. Usually this would be
// done in an init() function.
gob.Register(User{})
// Initialise a pointer to a new custom object.
user := &User{"Alice", "alice@example.com"}
// Store the custom object in the session data. Important: you should pass in
// a pointer to your object, not the value.
err := session.PutObject(r, "user", user)
if err != nil {
http.Error(w, err.Error(), 500)
}
}
*/
func PutObject(r *http.Request, key string, val interface{}) error {
if val == nil {
return errors.New("value must not be nil")
}
b, err := gobEncode(val)
if err != nil {
return err
}
return PutBytes(r, key, b)
}
// PopObject removes the data for a given session key and reads it into a custom
// object (represented by the dst parameter). It should only be used to retrieve
// custom data types that have been stored using PutObject. The object represented
// by dst will remain unchanged if the key does not exist.
//
// The dst parameter must be a pointer.
func PopObject(r *http.Request, key string, dst interface{}) error {
b, err := PopBytes(r, key)
if err != nil {
return err
}
if b == nil {
return nil
}
return gobDecode(b, dst)
}
// Keys returns a slice of all key names present in the session data, sorted
// alphabetically. If the session contains no data then an empty slice will be
// returned.
func Keys(r *http.Request) ([]string, error) {
s, err := sessionFromContext(r)
if err != nil {
return nil, err
}
s.mu.Lock()
keys := make([]string, len(s.data))
i := 0
for k, _ := range s.data {
keys[i] = k
i++
}
s.mu.Unlock()
sort.Strings(keys)
return keys, nil
}
// Exists returns true if the given key is present in the session data.
func Exists(r *http.Request, key string) (bool, error) {
s, err := sessionFromContext(r)
if err != nil {
return false, err
}
s.mu.Lock()
_, exists := s.data[key]
s.mu.Unlock()
return exists, nil
}
// Remove deletes the given key and corresponding value from the session data.
// If the key is not present this operation is a no-op.
func Remove(r *http.Request, key string) error {
s, err := sessionFromContext(r)
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.written == true {
return ErrAlreadyWritten
}
_, exists := s.data[key]
if exists == false {
return nil
}
delete(s.data, key)
s.modified = true
return nil
}
// Clear removes all data for the current session. The session token and lifetime
// are unaffected. If there is no data in the current session this operation is
// a no-op.
func Clear(r *http.Request) error {
s, err := sessionFromContext(r)
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.written == true {
return ErrAlreadyWritten
}
if len(s.data) == 0 {
return nil
}
for key := range s.data {
delete(s.data, key)
}
s.modified = true
return nil
}
func get(r *http.Request, key string) (interface{}, bool, error) {
s, err := sessionFromContext(r)
if err != nil {
return nil, false, err
}
s.mu.Lock()
v, exists := s.data[key]
s.mu.Unlock()
return v, exists, nil
}
func put(r *http.Request, key string, val interface{}) error {
s, err := sessionFromContext(r)
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.written == true {
return ErrAlreadyWritten
}
s.data[key] = val
s.modified = true
return nil
}
func pop(r *http.Request, key string) (interface{}, bool, error) {
s, err := sessionFromContext(r)
if err != nil {
return "", false, err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.written == true {
return "", false, ErrAlreadyWritten
}
v, exists := s.data[key]
if exists == false {
return nil, false, nil
}
delete(s.data, key)
s.modified = true
return v, true, nil
}
func gobEncode(v interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
err := gob.NewEncoder(buf).Encode(v)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func gobDecode(b []byte, dst interface{}) error {
buf := bytes.NewBuffer(b)
return gob.NewDecoder(buf).Decode(dst)
}