-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestore.go
81 lines (61 loc) · 1.48 KB
/
restore.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
package main
import (
"fmt"
"os"
badger "github.com/dgraph-io/badger"
)
func main() {
bak, err := os.Open("backup.bak")
if err != nil {
panic(err)
}
defer bak.Close()
opts := badger.DefaultOptions("./data-restored")
opts.Dir = "./data-restored"
opts.ValueDir = "./data-restored"
//opts.Logger = nil
//opts.Truncate = true
db, err := badger.Open(opts)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Load(bak, 16)
if err != nil {
panic(err)
}
err = db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte("marlon1"))
if err != nil {
panic(err)
}
var valNot, valCopy []byte
err = item.Value(func(val []byte) error {
// This func with val would only be called if item.Value encounters no error.
// Accessing val here is valid.
fmt.Printf("The answer is: %s\n", val)
// Copying or parsing val is valid.
valCopy = append([]byte{}, val...)
// Assigning val slice to another variable is NOT OK.
valNot = val // Do not do this.
return nil
})
if err != nil {
panic(err)
}
// DO NOT access val here. It is the most common cause of bugs.
fmt.Printf("NEVER do this. %s\n", valNot)
// You must copy it to use it outside item.Value(...).
fmt.Printf("The answer is: %s\n", valCopy)
// Alternatively, you could also use item.ValueCopy().
valCopy, err = item.ValueCopy(nil)
if err != nil {
panic(err)
}
fmt.Printf("The answer is: %s\n", valCopy)
return nil
})
if err != nil {
panic(err)
}
}