github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/data/cache/marshaler/marshaler.go (about) 1 package marshaler 2 3 import ( 4 "github.com/angenalZZZ/gofunc/data/cache" 5 "github.com/angenalZZZ/gofunc/data/cache/store" 6 "github.com/vmihailenco/msgpack" 7 "time" 8 ) 9 10 // Marshaler is the struct that marshal and unmarshal cache values 11 type Marshaler struct { 12 cache cache.Interface 13 } 14 15 // New creates a new marshaler that marshals/unmarshals cache values 16 func New(cache cache.Interface) *Marshaler { 17 return &Marshaler{ 18 cache: cache, 19 } 20 } 21 22 // Get obtains a value from cache and unmarshal value with given object 23 func (c *Marshaler) Get(key string, returnObj interface{}) (interface{}, error) { 24 result, err := c.cache.Get(key) 25 if err != nil { 26 return nil, err 27 } 28 29 switch result.(type) { 30 case []byte: 31 err = msgpack.Unmarshal(result.([]byte), returnObj) 32 33 case string: 34 err = msgpack.Unmarshal([]byte(result.(string)), returnObj) 35 } 36 37 if err != nil { 38 return nil, err 39 } 40 41 return returnObj, nil 42 } 43 44 // Set sets a value in cache by marshaling value 45 func (c *Marshaler) Set(key string, object interface{}, options *store.Options) error { 46 bytes, err := msgpack.Marshal(object) 47 if err != nil { 48 return err 49 } 50 51 return c.cache.Set(key, bytes, options) 52 } 53 54 // TTL returns an expiration time 55 func (c *Marshaler) TTL(key string) (time.Duration, error) { 56 return c.cache.TTL(key) 57 } 58 59 // Delete removes a value from the cache 60 func (c *Marshaler) Delete(key string) error { 61 return c.cache.Delete(key) 62 } 63 64 // Invalidate invalidate cache values using given options 65 func (c *Marshaler) Invalidate(options store.InvalidateOptions) error { 66 return c.cache.Invalidate(options) 67 } 68 69 // Clear reset all cache data 70 func (c *Marshaler) Clear() error { 71 return c.cache.Clear() 72 }