Created
April 27, 2017 16:39
-
-
Save maximelamure/9ca29cc43ae1a527b8f929e3c0ddc5ed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package cache | |
| import ( | |
| "bytes" | |
| "encoding/gob" | |
| "time" | |
| "github.com/bradfitz/gomemcache/memcache" | |
| ) | |
| type client struct { | |
| mc *memcache.Client | |
| } | |
| var ( | |
| c *client | |
| ) | |
| func Init(servers ...string) { | |
| mc := memcache.New(servers...) | |
| c = &client{mc: mc} | |
| } | |
| func Get(ctx context.Context, key string, obj interface{}) bool { | |
| if len(key) > 0 && c != nil { | |
| item, err := c.mc.Get(key) | |
| if err != nil { | |
| return false | |
| } | |
| if err := ObjFromBytes(item.Value, obj); err != nil { | |
| return false | |
| } | |
| return true | |
| } | |
| return false | |
| } | |
| func ObjFromBytes(b []byte, obj interface{}) error { | |
| dec := gob.NewDecoder(bytes.NewReader(b)) | |
| err := dec.Decode(obj) | |
| if err != nil { | |
| return err | |
| } | |
| return nil | |
| } | |
| // Set writes the given item, unconditionally. | |
| // expiration is the cache expiration time, in seconds: either a relative | |
| // time from now (up to 1 month), or an absolute Unix epoch time. | |
| // Zero means the Item has no expiration time. | |
| func Set(ctx context.Context, key string, object interface{}, expiration int32) error { | |
| if c != nil && len(key) > 0 { | |
| var b bytes.Buffer | |
| enc := gob.NewEncoder(&b) | |
| err := enc.Encode(object) | |
| if err != nil { | |
| return err | |
| } | |
| item := &memcache.Item{ | |
| Key: key, | |
| Value: b.Bytes(), | |
| Expiration: expiration, | |
| } | |
| return c.mc.Set(item) | |
| } | |
| return nil | |
| } | |
| func Delete(ctx context.Context, key string) error { | |
| return c.mc.Delete(key) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment