From 0d078fcad38cf5a5b54f5f547b5e5a6be4193e4e Mon Sep 17 00:00:00 2001 From: Masaki Yoshida Date: Fri, 9 Dec 2016 11:39:00 +0900 Subject: [PATCH] avoid to decode when item.Value is empty --- memd.go | 10 +++++++++- memd_test.go | 27 +++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/memd.go b/memd.go index e740777..f310c52 100644 --- a/memd.go +++ b/memd.go @@ -1,11 +1,16 @@ package memd import ( + "errors" + "log" + "github.com/douban/libmc/golibmc" "github.com/ugorji/go/codec" - "log" ) +// ErrEmptyValue is returned by FromItem when the size of item.Value is zero. +var ErrEmptyValue = errors.New("cannot decode from empty value") + // Client is wrapper of *golibmc.Client. type Client struct { *golibmc.Client @@ -121,6 +126,9 @@ func (c *Client) ToItem(key string, _val interface{}, exp int64) (*golibmc.Item, // FromItem ... deserialize item.Value func (c *Client) FromItem(item *golibmc.Item, val interface{}) error { + if len(item.Value) == 0 { + return ErrEmptyValue + } return codec.NewDecoderBytes(item.Value, c.serializer).Decode(val) } diff --git a/memd_test.go b/memd_test.go index 123c50f..262cc94 100644 --- a/memd_test.go +++ b/memd_test.go @@ -1,11 +1,12 @@ package memd import ( - "github.com/douban/libmc/golibmc" - "github.com/ugorji/go/codec" "log" "testing" "time" + + "github.com/douban/libmc/golibmc" + "github.com/ugorji/go/codec" ) type Result struct { @@ -125,3 +126,25 @@ func ResultSerializer(t *testing.T) { t.Error("invalid cache") } } + +func TestResultFromItem(t *testing.T) { + c := New(golibmc.SimpleNew([]string{"localhost:11211"})) + + tests := []struct { + b []byte + err error + }{ + {[]byte(``), ErrEmptyValue}, + {[]byte(`{}`), nil}, + {[]byte(`{"foo":"bar"}`), nil}, + } + + for _, tt := range tests { + item := &golibmc.Item{Value: tt.b} + var v map[string]interface{} + err := c.FromItem(item, &v) + if err != tt.err { + t.Errorf("FromItem(%+v, %s) = %#v", item, v, err) + } + } +}