Skip to content

Instantly share code, notes, and snippets.

@netfeed
Last active August 29, 2015 14:04
Show Gist options
  • Save netfeed/15ddae0c49cfaf754055 to your computer and use it in GitHub Desktop.
Save netfeed/15ddae0c49cfaf754055 to your computer and use it in GitHub Desktop.
Simple interface against groupcache to cache structs and then get it back from the cache
package cache
import (
"bytes"
"encoding/json"
"github.com/golang/groupcache"
)
type GetterFunc func(string) (interface{}, error)
func NewCache(name string, cacheBytes int64, fn GetterFunc) Cache {
cache := groupcache.NewGroup(name, cacheBytes, groupcache.GetterFunc(
func(ctx groupcache.Context, key string, dest groupcache.Sink) error {
strct, err := fn(key)
if err != nil {
return err
}
bytes, err := json.Marshal(strct)
if err != nil {
return err
}
dest.SetBytes(bytes)
return nil
}))
return Cache{cache}
}
type Cache struct {
Cache *groupcache.Group
}
func (cache Cache) Get(into interface{}, key string) error {
var data []byte
if err := cache.Cache.Get(nil, key, groupcache.AllocatingByteSliceSink(&data)); err != nil {
return err
}
if err := json.NewDecoder(bytes.NewReader(data)).Decode(into); err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment