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
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package cache
import (
"errors"
"log"
"os"
"go.etcd.io/bbolt"
)
var cache = []byte("cache")
func NewBoltStore(file string) *BoltStore {
db, err := bbolt.Open(file, 0644, nil)
if err != nil {
log.Printf("cache: failed to create database file %q: %v\n", file, err)
os.Exit(1)
}
c := &BoltStore{db: db}
return c
}
type BoltStore struct {
db *bbolt.DB
}
func (s *BoltStore) Get(key string) ([]byte, bool) {
var value []byte
err := s.db.View(func(tx *bbolt.Tx) error {
bucket := tx.Bucket(cache)
if bucket == nil {
return errors.New("bucket not found")
}
v := bucket.Get([]byte(key))
if v == nil {
return errors.New("key not found")
}
value = make([]byte, len(v))
copy(value, v)
return nil
})
if err != nil {
return nil, false
}
return value, true
}
func (s *BoltStore) Set(key string, value []byte) {
err := s.db.Update(func(tx *bbolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists(cache)
if err != nil {
return err
}
return bucket.Put([]byte(key), value)
})
if err != nil {
log.Printf("cache: failed to insert cache key %q: %v\n", key, err)
}
}
func (s *BoltStore) Close() {
s.db.Close()
}
|