From 00b041fbb0247f229539134d040730bc954c6f0e Mon Sep 17 00:00:00 2001 From: ChronosX88 Date: Thu, 27 May 2021 22:30:52 +0300 Subject: [PATCH] Use gob encoding for struct marshalling in redis cache --- cache/cache.go | 2 +- cache/inmemory_cache.go | 2 +- cache/redis_cache.go | 39 ++++++++++++++++++++++++++------------- 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/cache/cache.go b/cache/cache.go index bf23a26..1c155f8 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -5,7 +5,7 @@ import ( "time" ) -var ErrNilValue = errors.New("value is empty") +var ErrNotFound = errors.New("key doesn't exist in cache") type Cache interface { Store(key string, value interface{}) error diff --git a/cache/inmemory_cache.go b/cache/inmemory_cache.go index 2dacd46..828a9df 100644 --- a/cache/inmemory_cache.go +++ b/cache/inmemory_cache.go @@ -35,7 +35,7 @@ func (imc *InMemoryCache) StoreWithTTL(key string, value interface{}, ttl time.D func (imc *InMemoryCache) Get(key string, value interface{}) error { v, exists := imc.cache.Get(key) if !exists { - return ErrNilValue + return ErrNotFound } value = v diff --git a/cache/redis_cache.go b/cache/redis_cache.go index 0788dbe..ca06b0a 100644 --- a/cache/redis_cache.go +++ b/cache/redis_cache.go @@ -1,11 +1,13 @@ package cache import ( + "bytes" "context" + "encoding/gob" + "errors" "time" "github.com/Secured-Finance/dione/config" - "github.com/fxamacker/cbor/v2" "github.com/go-redis/redis/v8" ) @@ -28,41 +30,52 @@ func NewRedisCache(config *config.Config) *RedisCache { } func (rc *RedisCache) Store(key string, value interface{}) error { - mRes, err := cbor.Marshal(value) + data, err := gobMarshal(value) if err != nil { return err } - rc.Client.Set(rc.ctx, key, mRes, 0) + rc.Client.Set(rc.ctx, key, data, 0) return nil } func (rc *RedisCache) StoreWithTTL(key string, value interface{}, ttl time.Duration) error { - mRes, err := cbor.Marshal(value) + data, err := gobMarshal(value) if err != nil { return err } - - rc.Client.Set(rc.ctx, key, mRes, ttl) + rc.Client.Set(rc.ctx, key, data, ttl) return nil } +func gobMarshal(val interface{}) ([]byte, error) { + buf := bytes.NewBuffer(nil) + enc := gob.NewEncoder(buf) + err := enc.Encode(val) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func gobUnmarshal(data []byte, val interface{}) error { + buf := bytes.NewBuffer(data) + dec := gob.NewDecoder(buf) + return dec.Decode(&val) +} + func (rc *RedisCache) Get(key string, value interface{}) error { data, err := rc.Client.Get(rc.ctx, key).Bytes() if err != nil { - if err == redis.Nil { - return ErrNilValue + if errors.Is(err, redis.Nil) { + return ErrNotFound } return err } - err = cbor.Unmarshal(data, &value) - if err != nil { - return err - } - return nil + return gobUnmarshal(data, &value) } func (rc *RedisCache) Delete(key string) {