-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
54 lines (47 loc) · 984 Bytes
/
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
package main
import (
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
"github.com/heia-fr/telecom-tower/rollrenderer"
)
var store struct {
db *bolt.DB
}
func openDB(name string) error {
db, err := bolt.Open(name, 0600, nil)
if err != nil {
return err
}
store.db = db
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("Message"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return nil
})
return err
}
func closeDB() {
store.db.Close()
}
func saveMessage(m rollrenderer.TextMessage) {
store.db.Update(func(tx *bolt.Tx) error {
buf, err := json.Marshal(m)
if err != nil {
return err
}
b := tx.Bucket([]byte("Message"))
err = b.Put([]byte("last"), buf)
return err
})
}
func loadMessage() (res rollrenderer.TextMessage, err error) {
err = store.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("Message"))
v := b.Get([]byte("last"))
return json.Unmarshal(v, &res)
})
return
}