badguardhome/internal/storage/bolt/bolt.go

69 lines
1.2 KiB
Go

package bolt
import (
"bytes"
"encoding/gob"
"go.etcd.io/bbolt"
)
type DB struct {
bolt *bbolt.DB
}
func Open(filename string) (o *DB, err error) {
o = &DB{}
o.bolt, err = bbolt.Open(filename, 0o644, nil)
return o, err
}
func (d *DB) Close() (err error) {
if d.bolt != nil {
return d.bolt.Close()
}
return
}
func (d *DB) Store(root []byte, key []byte, val interface{}) error {
return d.bolt.Update(func(t *bbolt.Tx) error {
bkt, err := t.CreateBucketIfNotExists(root)
if err != nil {
return err
}
var buf bytes.Buffer
err = gob.NewEncoder(&buf).Encode(val)
if err != nil {
return err
}
err = bkt.Put(key, buf.Bytes())
if err != nil {
return err
}
return nil
})
}
func (d *DB) Load(root []byte, key []byte, val interface{}) error {
return d.bolt.View(func(t *bbolt.Tx) error {
bkt, err := t.CreateBucketIfNotExists(root)
if err != nil {
return err
}
err = gob.NewDecoder(bytes.NewBuffer(bkt.Get(key))).Decode(val)
if err != nil {
return err
}
return nil
})
}
func (d *DB) Delete(root []byte, key []byte) error {
return d.bolt.Update(func(t *bbolt.Tx) error {
bkt, err := t.CreateBucketIfNotExists(root)
if err != nil {
return err
}
return bkt.Delete(key)
})
}