Rssmon2/store/bolt.go

73 lines
1.5 KiB
Go
Executable File

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, asc bool, limit int) ([]string, error) {
if limit < 1 {
limit = 10000
}
found := []string{}
err := bc.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(namespace))
if bucket == nil {
return nil
}
c := bucket.Cursor()
if asc {
for k, _ := c.Seek([]byte(key)); k != nil && len(found) < limit; k, _ = c.Next() {
found = append(found, string(k))
}
} else {
c.Seek([]byte(key + "}}}}}}}}}}}}}}"))
for k, _ := c.Prev(); k != nil && len(found) < limit; k, _ = c.Prev() {
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
}