Created
April 20, 2024 01:22
-
-
Save ehfeng/8c5ea7aa3629702272993972a9f25a1f to your computer and use it in GitHub Desktop.
simple badger usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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