aboutsummaryrefslogtreecommitdiff
path: root/litecodec.go
blob: 0de46748974027396d44cf09af5ec2065563b3c1 (plain) (blame)
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
package securecookie

import "fmt"

var _ Codec = (*LiteCodec)(nil)

func NewLiteCodec() *LiteCodec {
	s := &LiteCodec{
		sz: GobEncoder{},
	}
	return s
}

// LiteCodec encodes and decodes
type LiteCodec struct {
	err error
	sz  Serializer
}

// Encoding sets the encoding/serialization method for cookies.
//
// Default is encoding/gob.  To encode special structures using encoding/gob,
// they must be registered first using gob.Register().
func (s *LiteCodec) SetSerializer(sz Serializer) *LiteCodec {
	s.sz = sz

	return s
}

// Encode encodes a value.
func (s *LiteCodec) Encode(name string, value interface{}) (string, error) {
	if s.err != nil {
		return "", s.err
	}
	var err error
	var b []byte
	// Serialize.
	if b, err = s.sz.Serialize(value); err != nil {
		return "", cookieError{cause: fmt.Errorf(`%w: %s`, err, name), typ: usageError}
	}
	// Done.
	return string(b), nil
}

// Decode decodes a value. The dst argument must be a pointer.
func (s *LiteCodec) Decode(name, value string, dst interface{}, _ ...int) error {
	if s.err != nil {
		return s.err
	}
	// Deserialize.
	if err := s.sz.Deserialize([]byte(value), dst); err != nil {
		return cookieError{cause: fmt.Errorf(`%w: %s`, err, name), typ: decodeError}
	}
	// Done.
	return nil
}