diff options
author | Matt Silverlock <matt@eatsleeprepeat.net> | 2017-02-22 05:13:50 +0300 |
---|---|---|
committer | Matt Silverlock <matt@eatsleeprepeat.net> | 2017-02-22 05:13:50 +0300 |
commit | fbc587a6f03fd73ab27cc614367a1d3d0244ee90 (patch) | |
tree | a90bd4512b922910249a0393a34b7e6fbb0c719e /serialize.go | |
parent | 55fb70d4b7445f35318cdde4f62437408566708e (diff) |
[wip] first v2 cut.elithrar/v2
- Move to using crypto/nacl/secretbox for enc/dec
- Restructure how options are handled
- TODO: review serialization interface
- TODO: refactor multicodec support for rotated keys
Diffstat (limited to 'serialize.go')
-rw-r--r-- | serialize.go | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/serialize.go b/serialize.go new file mode 100644 index 0000000..2d1e8e7 --- /dev/null +++ b/serialize.go @@ -0,0 +1,64 @@ +package securecookie + +import ( + "bytes" + "encoding/gob" + "encoding/json" +) + +// Serialize encodes a value using gob. +func (e GobEncoder) Serialize(src interface{}) ([]byte, error) { + buf := new(bytes.Buffer) + enc := gob.NewEncoder(buf) + if err := enc.Encode(src); err != nil { + return nil, cookieError{cause: err, typ: usageError} + } + return buf.Bytes(), nil +} + +// Deserialize decodes a value using gob. +func (e GobEncoder) Deserialize(src []byte, dst interface{}) error { + dec := gob.NewDecoder(bytes.NewBuffer(src)) + if err := dec.Decode(dst); err != nil { + return cookieError{cause: err, typ: decodeError} + } + return nil +} + +// Serialize encodes a value using encoding/json. +func (e JSONEncoder) Serialize(src interface{}) ([]byte, error) { + buf := new(bytes.Buffer) + enc := json.NewEncoder(buf) + if err := enc.Encode(src); err != nil { + return nil, cookieError{cause: err, typ: usageError} + } + return buf.Bytes(), nil +} + +// Deserialize decodes a value using encoding/json. +func (e JSONEncoder) Deserialize(src []byte, dst interface{}) error { + dec := json.NewDecoder(bytes.NewReader(src)) + if err := dec.Decode(dst); err != nil { + return cookieError{cause: err, typ: decodeError} + } + return nil +} + +// Serialize passes a []byte through as-is. +func (e NopEncoder) Serialize(src interface{}) ([]byte, error) { + if b, ok := src.([]byte); ok { + return b, nil + } + + return nil, errValueNotByte +} + +// Deserialize passes a []byte through as-is. +func (e NopEncoder) Deserialize(src []byte, dst interface{}) error { + if _, ok := dst.([]byte); ok { + dst = src + return nil + } + + return errValueNotByte +} |