-
Notifications
You must be signed in to change notification settings - Fork 171
/
codec.go
51 lines (42 loc) · 1.25 KB
/
codec.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
package scs
import (
"bytes"
"encoding/gob"
"time"
)
// Codec is the interface for encoding/decoding session data to and from a byte
// slice for use by the session store.
type Codec interface {
Encode(deadline time.Time, values map[string]interface{}) ([]byte, error)
Decode([]byte) (deadline time.Time, values map[string]interface{}, err error)
}
// GobCodec is used for encoding/decoding session data to and from a byte
// slice using the encoding/gob package.
type GobCodec struct{}
// Encode converts a session deadline and values into a byte slice.
func (GobCodec) Encode(deadline time.Time, values map[string]interface{}) ([]byte, error) {
aux := &struct {
Deadline time.Time
Values map[string]interface{}
}{
Deadline: deadline,
Values: values,
}
var b bytes.Buffer
if err := gob.NewEncoder(&b).Encode(&aux); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// Decode converts a byte slice into a session deadline and values.
func (GobCodec) Decode(b []byte) (time.Time, map[string]interface{}, error) {
aux := &struct {
Deadline time.Time
Values map[string]interface{}
}{}
r := bytes.NewReader(b)
if err := gob.NewDecoder(r).Decode(&aux); err != nil {
return time.Time{}, nil, err
}
return aux.Deadline, aux.Values, nil
}