shock/example_seq_test.go
jolheiser de4e822f7d
Refactor to using Init funcs and add gob serializer
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2020-08-03 16:11:20 -05:00

64 lines
1.2 KiB
Go

package shock
import (
"fmt"
"io/ioutil"
"os"
"path"
)
// TestUser object
type TestUser struct {
ID uint64 `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
Admin bool `json:"admin"`
}
// Implement the interface for Sequencer
func (t *TestUser) AssignSeq(seq uint64) {
t.ID = seq
}
func ExampleTestUser() {
dir, err := ioutil.TempDir(os.TempDir(), "shock")
if err != nil {
panic(err)
}
dbPath := path.Join(dir, "shock.db")
db, err = Open(dbPath, os.ModePerm, DefaultOptions)
if err != nil {
panic(err)
}
// Get a bucket to work with instead of specifying each time
bucket := db.Bucket("test-user")
if err := bucket.Init(); err != nil {
panic(err)
}
// Add a new TestUser
t := &TestUser{
Name: "Tester123",
Age: 25,
Admin: true,
}
if err := bucket.Put(t); err != nil {
panic(err)
}
// Get the TestUser from the DB later (via sequence ID)
var tt TestUser
if err := bucket.Get(t.ID, &tt); err != nil {
panic(err)
}
if err := db.Bolt.Close(); err != nil {
fmt.Printf("Could not close DB %s: %v\n", dbPath, err)
}
if err := os.RemoveAll(dir); err != nil {
fmt.Printf("Could not delete temp dir %s: %v\n", dir, err)
}
}