-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathjson.go
57 lines (46 loc) · 1 KB
/
json.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
package sweetdb
import (
"bytes"
"encoding/json"
"github.com/go-errors/errors"
bolt "go.etcd.io/bbolt"
)
func (db *DB) setJSON(bucket []byte, bucketKey []byte, v interface{}) error {
payload, err := json.Marshal(v)
if err != nil {
return err
}
return db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists(bucket)
if err != nil {
return err
}
if err := bucket.Put(bucketKey, payload); err != nil {
return err
}
return nil
})
}
func (db *DB) getJSON(bucketName []byte, bucketKey []byte, v interface{}) error {
err := db.View(func(tx *bolt.Tx) error {
// First fetch the bucket
bucket := tx.Bucket(bucketName)
if bucket == nil {
return nil
}
payload := bucket.Get(bucketKey)
if payload == nil || bytes.Equal(payload, []byte("null")) {
v = nil
return nil
}
err := json.Unmarshal(payload, v)
if err != nil {
return errors.Errorf("Could not unmarshal data: %v", err)
}
return nil
})
if err != nil {
return err
}
return nil
}