-
Notifications
You must be signed in to change notification settings - Fork 18
/
boltdb.go
62 lines (48 loc) · 1.33 KB
/
boltdb.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
package main
import (
"github.com/boltdb/bolt"
"log"
)
func main() {
db, err := bolt.Open("bolt.db", 0666, nil)
if err != nil {
log.Println(err)
}
defer db.Close()
// Execute several commands within a write transaction.
err = db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte("widgets"))
if err != nil {
return err
}
if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
return err
}
c, err := b.CreateBucketIfNotExists([]byte("nested"))
if err != nil {
return err
}
err = c.Put([]byte("nested.foo"), []byte("nested.foo"))
return nil
})
// If our transactional block didn't return an error then our data is saved.
if err == nil {
messages := make(chan string)
db.View(func(tx *bolt.Tx) error {
value := tx.Bucket([]byte("widgets")).Get([]byte("foo"))
//log.Println(value)
log.Printf("The value of 'foo' within the transaction is: %s\n", value)
go func() { messages <- string(value) }()
return nil
})
msg := <-messages
log.Printf("The value of 'foo' outside the transaction is: %s\n", msg)
}
//view nested bucket
db.View(func(tx *bolt.Tx) error {
value := tx.Bucket([]byte("widgets")).Bucket([]byte("nested")).Get([]byte("nested.foo"))
//log.Println(value)
log.Printf("The value of 'nested.foo' is: %s\n", value)
return nil
})
}