~evanj/cms

ref: 37b75b6fd4e482657f38cb98668b78df49c66971 cms/internal/s/cache/cache.go -rw-r--r-- 941 bytes
37b75b6fEvan M Jones TEST(cache): Attempting to cache at controller level. 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package cache

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/bradfitz/gomemcache/memcache"
)

type Cache struct {
	log     *log.Logger
	baseKey string
	mc      *memcache.Client
}

func New(log *log.Logger, key string, memcacheServer string) (*Cache, error) {
	c := &Cache{log, key, memcache.New(memcacheServer)}
	return c, c.mc.Ping()
}

func (c *Cache) Key(things ...string) string {
	key := fmt.Sprintf("%s", c.baseKey)
	for _, thing := range things {
		key = fmt.Sprintf("%s::%s", key, thing)
	}
	return key
}

func (c *Cache) Get(key string, item interface{}) error {
	thing, err := c.mc.Get(key)
	if err != nil {
		return err
	}
	return json.Unmarshal(thing.Value, item)
}

func (c *Cache) Set(key string, thing interface{}) error {
	bytes, err := json.Marshal(thing)
	if err != nil {
		return err
	}
	return c.mc.Set(&memcache.Item{Key: key, Value: bytes})
}

func (c *Cache) Del(key string) error {
	return c.mc.Delete(key)
}