This repository has been archived by the owner on Mar 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
cache.go
104 lines (88 loc) · 2.26 KB
/
cache.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package photoshare
import (
"encoding/base64"
"encoding/json"
"github.com/bradfitz/gomemcache/memcache"
"github.com/juju/errgo"
"net/http"
"strings"
)
const defaultExpiration = 300 // 5 minutes
type cache interface {
set(string, interface{}) ([]byte, error)
get(string, func() (interface{}, error)) (interface{}, error)
clear() error
render(http.ResponseWriter, int, string, func() (interface{}, error)) error
}
func makeCacheKey(s string) string {
return base64.StdEncoding.EncodeToString([]byte(s))
}
type memcacheCache struct {
mc *memcache.Client
}
func (m *memcacheCache) set(key string, obj interface{}) ([]byte, error) {
value, err := json.Marshal(obj)
if err != nil {
return value, err
}
item := &memcache.Item{
Key: key,
Value: value,
Expiration: defaultExpiration,
}
if err := m.mc.Set(item); err != nil {
return value, errgo.Mask(err)
}
return value, nil
}
func (m *memcacheCache) get(key string, fn func() (interface{}, error)) (interface{}, error) {
key = makeCacheKey(key)
it, err := m.mc.Get(key)
if err == nil {
var obj interface{}
if err := json.Unmarshal(it.Value, obj); err != nil {
return obj, errgo.Mask(err)
}
return obj, nil
} else if err != memcache.ErrCacheMiss {
return nil, errgo.Mask(err)
}
obj, err := fn()
if err != nil {
return obj, err
}
if _, err := m.set(key, obj); err != nil {
return obj, errgo.Mask(err)
}
return obj, nil
}
// fetches or catches result of fn as JSON, and renders JSON to response
func (m *memcacheCache) render(w http.ResponseWriter, status int, key string, fn func() (interface{}, error)) error {
var write = func(value []byte) error {
return writeBody(w, value, status, "application/json")
}
key = makeCacheKey(key)
it, err := m.mc.Get(key)
if err == nil {
return write(it.Value)
} else if err != memcache.ErrCacheMiss {
return errgo.Mask(err)
}
obj, err := fn()
if err != nil {
return err
}
value, err := m.set(key, obj)
if err != nil {
return errgo.Mask(err)
}
return write(value)
}
func (m *memcacheCache) clear() error {
return errgo.Mask(m.mc.DeleteAll())
}
// NewCache creates a new Cache instance
func newCache(cfg *config) cache {
mc := memcache.New(strings.Split(cfg.MemcacheHost, ",")...) // will be from cfg
return &memcacheCache{mc}
}