-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathboltUtil.go
61 lines (53 loc) · 1.13 KB
/
boltUtil.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
package ssgo
import (
"encoding/json"
"fmt"
"os"
"time"
"github.com/boltdb/bolt"
)
var db *bolt.DB
func init() {
boltPath := os.Getenv("ssgo.boltdb")
if boltPath == "" {
boltPath = "ssgo.db"
}
var err error
db, err = bolt.Open(boltPath, 0600, &bolt.Options{Timeout: 2 * time.Second})
if err != nil {
panic(err.Error())
}
}
func StoreBoltJson(bucket string, key string, data interface{}) error {
j, err := json.Marshal(data)
if err != nil {
return err
}
return db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
err := b.Put([]byte(key), j)
return err
})
}
func LookupBoltJson(bucket string, key string, v interface{}) error {
return db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
data := b.Get([]byte(key))
if data == nil {
return fmt.Errorf("Not found")
}
return json.Unmarshal(data, v)
})
}
func EnsureBoltBucketExists(bucket string) error {
return db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(bucket))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return nil
})
}
func GetDb() *bolt.DB {
return db
}