-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiskv_example_test.go
73 lines (59 loc) · 1.51 KB
/
diskv_example_test.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
package diskvd_test
import (
"fmt"
"os"
"path/filepath"
diskvd "github.com/lucmq/go-shelve/driver/db/diskv"
"github.com/lucmq/go-shelve/shelve"
)
var StoragePath = filepath.Join(os.TempDir(), "game-test", "db")
type Player struct {
Name string
Level int
Gold int
Items []string
}
type Config struct {
Difficulty string
}
// NewShelf creates a customized Shelf using Diskv and JSON.
func NewShelf[V any](path string) (*shelve.Shelf[string, V], error) {
path = filepath.Join(StoragePath, path)
extension := "json" // Extension of the record files
db, err := diskvd.NewDefault(path, extension)
if err != nil {
return nil, err
}
return shelve.Open[string, V](
path,
shelve.WithDatabase(db),
shelve.WithCodec(shelve.JSONCodec()),
)
}
func Example() {
// Open the shelf with custom options
players, _ := NewShelf[Player]("players")
config, _ := NewShelf[Config]("config")
defer players.Close()
defer config.Close()
// Create the game data
player := Player{
Name: "Frodo",
Level: 14,
Gold: 9999,
Items: []string{"Sting", "Lembas"},
}
cfg := Config{
Difficulty: "Hard",
}
// Save the data. Serialization and persistence will be
// handled automatically by the Shelf.
players.Put(player.Name, player)
config.Put("config", cfg)
// The app storage will contain readable JSON files with
// configuration and game state, that can be retrieved
// back to a Go type:
value, ok, _ := players.Get("Frodo")
fmt.Println(ok, value.Name, value.Items)
// Output: true Frodo [Sting Lembas]
}