Skip to content

Instantly share code, notes, and snippets.

@ehfeng
Created August 30, 2023 00:30
Show Gist options
  • Save ehfeng/225de262d45c7275b3f0ede2d7917b4b to your computer and use it in GitHub Desktop.
Save ehfeng/225de262d45c7275b3f0ede2d7917b4b to your computer and use it in GitHub Desktop.
You can store nil values in bbolt. In ForEach, the only way to determine if a key is a nil value or bucket is by attempting to cast it as a bucket.
package main
import (
"fmt"
"go.etcd.io/bbolt"
)
var bucketName = []byte("MyBucket")
func main() {
db, err := bbolt.Open("my.db", 0600, nil)
if err != nil {
panic(err)
}
defer db.Close()
if err := db.Update(func(tx *bbolt.Tx) error {
b, err := tx.CreateBucketIfNotExists(bucketName)
if err != nil {
return err
}
return b.Put([]byte("answer"), nil)
}); err != nil {
panic(err)
}
if err := db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket(bucketName)
return b.ForEach(func(k, v []byte) error {
fmt.Println(string(k), string(v))
return nil
})
}); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment