-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
95 lines (83 loc) · 2.05 KB
/
store.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
package main
import "github.com/boltdb/bolt"
import "errors"
type KvStore interface {
Put(key []byte, value []byte) error
Delete(key []byte) error
Get(key []byte) (value []byte, err error)
Close()
}
type kvStore struct {
db *bolt.DB
bucketName []byte
}
func NewKvStore(options map[string]interface{}) (KvStore, error) {
var path string
var bucketName []byte
if val, ok := options["datapath"].(string); ok {
path = val
} else {
return nil, errors.New("require options datapath for KvStore")
}
if val, ok := options["bucketName"].([]byte); ok {
bucketName = val
} else {
return nil, errors.New("require options bucketName for KvStore")
}
db, err := bolt.Open(path, 0600, nil)
kv := &kvStore{db: db, bucketName: bucketName}
kv.createBucket()
return kv, err
}
func (b *kvStore) Put(key []byte, value []byte) error {
bucketName := b.bucketName
return b.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(bucketName)
if bucket == nil {
return errors.New("bucket does not exists:" + string(bucketName))
}
if err := bucket.Put(key, value); err != nil {
return err
}
return nil
})
}
func (b *kvStore) Get(key []byte) (value []byte, err error) {
bucketName := b.bucketName
err = b.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(bucketName)
if bucket == nil {
return errors.New("bucket does not exists:" + string(bucketName))
}
value = bucket.Get(key)
return nil
})
return value, err
}
func (b *kvStore) Delete(key []byte) error {
bucketName := b.bucketName
return b.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(bucketName)
if bucket == nil {
return errors.New("bucket does not exists:" + string(bucketName))
}
err := bucket.Delete(key)
if err != nil {
return err
}
return nil
})
}
func (b *kvStore) createBucket() (err error) {
bucketName := b.bucketName
return b.db.Update(func(tx *bolt.Tx) error {
_, err = tx.CreateBucketIfNotExists(bucketName)
if err != nil && err != bolt.ErrBucketExists {
return err
}
return nil
})
}
func (b *kvStore) Close() {
b.db.Close()
}