Skip to content

Instantly share code, notes, and snippets.

@ehfeng
Created April 20, 2024 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehfeng/8c5ea7aa3629702272993972a9f25a1f to your computer and use it in GitHub Desktop.
Save ehfeng/8c5ea7aa3629702272993972a9f25a1f to your computer and use it in GitHub Desktop.
simple badger usage
package main
import (
"encoding/binary"
"fmt"
"sync"
"github.com/dgraph-io/badger/v4"
)
func main() {
opts := badger.DefaultOptions("/tmp/badger")
opts.Logger = nil
db, err := badger.Open(opts)
if err != nil {
panic(err)
}
defer db.Close()
if err := db.DropAll(); err != nil {
panic(err)
}
func() {
txn := db.NewTransaction(true)
defer txn.Discard()
if err := txn.Set([]byte("a"), []byte("0")); err != nil {
panic(err)
}
if err := txn.Commit(); err != nil {
panic(err)
}
}()
if err := db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte("a"))
if err != nil {
panic(err)
}
return item.Value(func(val []byte) error {
fmt.Println("get", string(val))
return nil
})
}); err != nil {
panic(err)
}
func() {
txn := db.NewTransaction(false)
defer txn.Discard()
it := txn.NewIterator(badger.DefaultIteratorOptions)
defer it.Close()
it.Rewind()
if it.Valid() {
i := it.Item()
k := i.Key()
fmt.Println("iterator", string(k))
} else {
fmt.Println("no key")
}
}()
if err := db.DropAll(); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment