From 155134204c034796bcd7a72c1e1b53ba005735c6 Mon Sep 17 00:00:00 2001 From: Kamil Kisiel Date: Thu, 17 Oct 2013 10:33:57 -0700 Subject: Better errors for {En,De}codeMulti. --- securecookie.go | 16 ++++++++++++---- securecookie_test.go | 13 +++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/securecookie.go b/securecookie.go index 892b412..2f34bfe 100644 --- a/securecookie.go +++ b/securecookie.go @@ -357,12 +357,17 @@ func CodecsFromPairs(keyPairs ...[]byte) []Codec { return codecs } +var errNoCodecs = errors.New("securecookie: no codecs provided") + // EncodeMulti encodes a cookie value using a group of codecs. // // The codecs are tried in order. Multiple codecs are accepted to allow // key rotation. -func EncodeMulti(name string, value interface{}, - codecs ...Codec) (string, error) { +func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) { + if len(codecs) == 0 { + return "", errNoCodecs + } + var errors MultiError for _, codec := range codecs { if encoded, err := codec.Encode(name, value); err == nil { @@ -378,8 +383,11 @@ func EncodeMulti(name string, value interface{}, // // The codecs are tried in order. Multiple codecs are accepted to allow // key rotation. -func DecodeMulti(name string, value string, dst interface{}, - codecs ...Codec) error { +func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error { + if len(codecs) == 0 { + return errNoCodecs + } + var errors MultiError for _, codec := range codecs { if err := codec.Decode(name, value, dst); err == nil { diff --git a/securecookie_test.go b/securecookie_test.go index 099c290..fe0cdb1 100644 --- a/securecookie_test.go +++ b/securecookie_test.go @@ -144,6 +144,19 @@ func TestMultiError(t *testing.T) { } } +func TestMultiNoCodecs(t *testing.T) { + _, err := EncodeMulti("foo", "bar") + if err != errNoCodecs { + t.Errorf("EncodeMulti: bad value for error, got: %v", err) + } + + var dst []byte + err = DecodeMulti("foo", "bar", &dst) + if err != errNoCodecs { + t.Errorf("DecodeMulti: bad value for error, got: %v", err) + } +} + // ---------------------------------------------------------------------------- type FooBar struct { -- cgit v1.2.3