Skip to content

Instantly share code, notes, and snippets.

@theophoric
Last active November 17, 2022 13:02
Show Gist options
  • Save theophoric/9535195 to your computer and use it in GitHub Desktop.
Save theophoric/9535195 to your computer and use it in GitHub Desktop.
How to store + decode objects in golang using leveldb + gob
package main
import (
"bytes"
"encoding/gob"
"fmt"
"time"
"github.com/syndtr/goleveldb/leveldb"
)
type Node struct {
id string
body string
CreatedAt time.Time
UpdatedAt time.Time
}
var (
NodeStorage *leveldb.DB
NodeMemory = make(map[string]*Node)
)
func main() {
var err error
NodeStorage, err = leveldb.OpenFile("level", nil)
if err != nil {
fmt.Println(err.Error())
return
}
now := time.Now()
n := Node{"42", "body", now, now}
err = n.Save()
if err != nil {
fmt.Println(err.Error())
return
}
nn, err := FindNode("42")
nn.body = "another body"
nn.Save()
nn2, err := FindNode("42")
fmt.Println(nn2)
}
func FindNode(nodeId string) (node *Node, err error) {
node, inMem := NodeMemory[nodeId]
if !inMem {
var data []byte
data, err = NodeStorage.Get([]byte(nodeId), nil)
if err != nil {
return
}
dec := gob.NewDecoder(bytes.NewReader(data))
dec.Decode(node)
}
return
}
func (n *Node) Delete() (node Node, err error) {
err = NodeStorage.Delete([]byte(n.id), nil)
if err != nil {
return
}
delete(NodeMemory, n.id)
node = *n
return
}
func (n *Node) Save() (err error) {
n.UpdatedAt = time.Now()
var data bytes.Buffer
enc := gob.NewEncoder(&data)
enc.Encode(*n)
err = NodeStorage.Put([]byte(n.id), data.Bytes(), nil)
if err != nil {
return
}
if _, inMemory := NodeMemory[n.id]; !inMemory {
NodeMemory[n.id] = n
}
return
}
@theophoric
Copy link
Author

( untested, btw )

@adamflott
Copy link

Just stopping by to say thanks for the example!

@Volant
Copy link

Volant commented Feb 2, 2021

dec.Decode(node) should be written as dec.Decode(&node)

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