forked from mat/besticon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
caching.go
83 lines (69 loc) · 1.58 KB
/
caching.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
package besticon
import (
"encoding/json"
"errors"
"fmt"
"time"
"github.com/golang/groupcache"
)
var iconCache *groupcache.Group
type result struct {
Icons []Icon
Error string
}
func resultFromCache(siteURL string) ([]Icon, error) {
if iconCache == nil {
return fetchIcons(siteURL)
}
// Let results expire after a day
now := time.Now()
key := fmt.Sprintf("%d-%02d-%02d-%s", now.Year(), now.Month(), now.Day(), siteURL)
var data []byte
err := iconCache.Get(siteURL, key, groupcache.AllocatingByteSliceSink(&data))
if err != nil {
logger.Println("ERR:", err)
return fetchIcons(siteURL)
}
res := &result{}
err = json.Unmarshal(data, res)
if err != nil {
panic(err)
}
if res.Error != "" {
return res.Icons, errors.New(res.Error)
}
return res.Icons, nil
}
func generatorFunc(ctx groupcache.Context, key string, sink groupcache.Sink) error {
siteURL := ctx.(string)
icons, err := fetchIcons(siteURL)
if err != nil {
// Don't cache errors
return err
}
res := result{Icons: icons}
if err != nil {
res.Error = err.Error()
}
bytes, err := json.Marshal(res)
if err != nil {
panic(err)
}
sink.SetBytes(bytes)
return nil
}
func CacheEnabled() bool {
return iconCache != nil
}
// SetCacheMaxSize enables icon caching if sizeInMB > 0.
func SetCacheMaxSize(sizeInMB int64) {
if sizeInMB > 0 {
iconCache = groupcache.NewGroup("icons", sizeInMB<<20, groupcache.GetterFunc(generatorFunc))
} else {
iconCache = nil
}
}
// GetCacheStats returns cache statistics.
func GetCacheStats() groupcache.CacheStats {
return iconCache.CacheStats(groupcache.MainCache)
}