-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
68 lines (60 loc) · 1.51 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
// Package cache provides a caching implementation that uses the diskv package
// to supplement an in-memory map with persistent storage.
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"io"
"log"
"github.com/peterbourgon/diskv"
)
type Cache struct {
d *diskv.Diskv
}
func NewCache(basePath string) *Cache {
return &Cache{
d: diskv.New(diskv.Options{
BasePath: basePath,
CacheSizeMax: 100 * 1024 * 1024, // 100MB
}),
}
}
func (c *Cache) Get(key string) (value []byte, ok bool) {
filename := keyToFilename(key)
if filename == "" {
log.Printf("Skipping unusable cache: %v", filename)
return []byte{}, false
}
value, err := c.d.Read(filename)
if err != nil {
log.Print("Cache MISS: ", key)
return []byte{}, false
}
log.Print("Cache HIT: ", key)
return value, true
}
func (c *Cache) Set(key string, value []byte) {
filename := keyToFilename(key)
if err := c.d.WriteStream(filename, bytes.NewReader(value), true); err != nil {
log.Printf("Failed to write %v to cache: %v", key, err)
return
}
log.Print("Cache SET: ", key)
}
func (c *Cache) Delete(key string) {
filename := keyToFilename(key)
if err := c.d.Erase(filename); err != nil {
log.Printf("Failed to delete %v from cache: %v", key, err)
return
}
log.Print("Cache DELETE: ", key)
}
func keyToFilename(key string) string {
hash := sha1.New()
if _, err := io.WriteString(hash, key); err != nil {
log.Printf("Failed to generate cache filename from key: %v", err)
return ""
}
return hex.EncodeToString(hash.Sum(nil))
}