63 lines
1.2 KiB
Go
63 lines
1.2 KiB
Go
package store
|
|
|
|
import (
|
|
"github.com/boltdb/bolt"
|
|
)
|
|
|
|
type BoltClient struct {
|
|
db *bolt.DB
|
|
}
|
|
|
|
func NewBolt(path string) (*BoltClient, error) {
|
|
db, err := bolt.Open(path, 0600, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &BoltClient{
|
|
db: db,
|
|
}, nil
|
|
}
|
|
|
|
func (bc *BoltClient) Close() error {
|
|
return bc.db.Close()
|
|
}
|
|
|
|
func (bc *BoltClient) Set(namespace, key string, value []byte) error {
|
|
return bc.db.Update(func(tx *bolt.Tx) error {
|
|
bucket, err := tx.CreateBucketIfNotExists([]byte(namespace))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return bucket.Put([]byte(key), value)
|
|
})
|
|
}
|
|
|
|
func (bc *BoltClient) List(namespace, key string) ([]string, error) {
|
|
found := []string{}
|
|
err := bc.db.View(func(tx *bolt.Tx) error {
|
|
bucket := tx.Bucket([]byte(namespace))
|
|
if bucket == nil {
|
|
return nil
|
|
}
|
|
c := bucket.Cursor()
|
|
for k, _ := c.Seek([]byte(key)); k != nil; k, _ = c.Next() {
|
|
found = append(found, string(k))
|
|
}
|
|
return nil
|
|
})
|
|
return found, err
|
|
}
|
|
|
|
func (bc *BoltClient) Get(namespace, key string) ([]byte, error) {
|
|
var result []byte
|
|
err := bc.db.View(func(tx *bolt.Tx) error {
|
|
bucket := tx.Bucket([]byte(namespace))
|
|
if bucket == nil {
|
|
return nil
|
|
}
|
|
result = bucket.Get([]byte(key))
|
|
return nil
|
|
})
|
|
return result, err
|
|
}
|