diff options
Diffstat (limited to 'unsafecodec.go')
-rw-r--r-- | unsafecodec.go | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/unsafecodec.go b/unsafecodec.go new file mode 100644 index 0000000..6853658 --- /dev/null +++ b/unsafecodec.go @@ -0,0 +1,56 @@ +package securecookie + +import "fmt" + +var _ Codec = (*UnsafeCodec)(nil) + +func NewUnsafeCodec() *UnsafeCodec { + s := &UnsafeCodec{ + sz: GobEncoder{}, + } + return s +} + +// UnsafeCodec encodes and decodes +type UnsafeCodec 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 *UnsafeCodec) SetSerializer(sz Serializer) *UnsafeCodec { + s.sz = sz + + return s +} + +// Encode encodes a value. +func (s *UnsafeCodec) 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 *UnsafeCodec) 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 +} |