-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcache.go
54 lines (47 loc) · 875 Bytes
/
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
package main
import (
"fmt"
"log"
"github.com/boltdb/bolt"
)
type Cache struct {
db *bolt.DB
}
func newCache() *Cache {
db, err := bolt.Open("cache.db", 0600, nil)
if err != nil {
log.Fatal(err)
}
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("cache"))
if err != nil {
return fmt.Errorf("create bucket (cache): %v", err)
}
return nil
})
return &Cache{
db: db,
}
}
func (c *Cache) set(k string, v []byte) {
err := c.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("cache"))
err := b.Put([]byte(k), v)
return err
})
if err != nil {
log.Fatal(err)
}
}
func (c *Cache) get(k string) []byte {
var val []byte
c.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("cache"))
val = b.Get([]byte(k))
return nil
})
return val
}
func (c *Cache) close() error {
return c.db.Close()
}