Skip to content

Instantly share code, notes, and snippets.

@marshyon
Last active July 25, 2024 14:36
Show Gist options
  • Save marshyon/51c7d010e5b41ac65b9efbaf810338bf to your computer and use it in GitHub Desktop.
Save marshyon/51c7d010e5b41ac65b9efbaf810338bf to your computer and use it in GitHub Desktop.
Golang badger db using GOB to serialise object data into badger fields
/*
*
* Golang badger db using GOB to serialize object data into badger fields
*
* Golang has its very own serializer / deserializer - Go Object (gob) so why not use it where data passed is entirely within a Go
* application ?
*
* JSON or some other text based solution could be used but gob might be faster.
*
* A gob encoder accepts the type bytes.Buffer to encode data to, so to write this to Badger, which accepts the type byte
* this is converted using bytes.Buffer Bytes function to convert it.
*
* Subssequently to read back the type bytes into a gob decoder, bytes.NewReader converts type bytes back to bytes.Buffer for a
* gob decoder to de-serialize the data.
*
*/
package main
import (
"bytes"
"encoding/gob"
"fmt"
"log"
badger "github.com/dgraph-io/badger"
)
type Student struct {
Name string
Age int32
}
func main() {
opts := badger.DefaultOptions("/tmp/badger")
opts.Logger = nil
db, err := badger.Open(opts)
if err != nil {
log.Fatal(err)
}
defer db.Close()
studentEncode := Student{Name: "Peter", Age: 36}
var b bytes.Buffer
e := gob.NewEncoder(&b)
if err := e.Encode(studentEncode); err != nil {
panic(err)
}
err = db.Update(func(txn *badger.Txn) error {
err := txn.Set([]byte("answer"), b.Bytes())
return err
})
if err != nil {
fmt.Printf("ERROR saving to badger db : %s\n", err)
}
key := "answer"
err = db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte(key))
if err != nil {
return err
}
val, err := item.ValueCopy(nil)
if err != nil {
return err
}
var studentDecode Student
d := gob.NewDecoder(bytes.NewReader(val))
if err := d.Decode(&studentDecode); err != nil {
panic(err)
}
log.Printf("Decoded Struct from badger : name [%s] age [%d]\n", studentDecode.Name, studentDecode.Age)
return nil
})
}
@marshyon
Copy link
Author

marshyon commented Aug 6, 2021

apparently there are breaking changes to the opts and Item.value functionality from 1.6.0 onwards, updated this to use 'ValueCopy' and new DefaultOptions with just a string containing the path to the DB, in this case, /tmp - change it to be where it is needed to be so long as it exists and is writable. The badger directory gets created by badger itself if it is not already there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment