package storage
import (
"fmt"
"os"
)
const DEFAULT_STORAGE_ENGINE = "bolt" //默认存储引擎 为 bolt
//存储引擎map集合
var supportedStorage = map[string]func(path string) (Storage, error){
"kv": openKVStorage,
"bolt": openBoltStorage,
}
//存储引擎注册
func RegisterStorageEngine(name string, fn func(path string) (Storage, error)) {
supportedStorage[name] = fn
}
//存储引擎接口
type Storage interface {
Set(k, v []byte) error
Get(k []byte) ([]byte, error)
Delete(k []byte) error
ForEach(fn func(k, v []byte) error) error
Close() error
WALName() string
}
//打开存储引擎 存储引擎 优先使用用户自定的引擎 ,默认引擎为bolt 。如果不存在 使用默认引擎
func OpenStorage(path string) (Storage, error) {
wse := os.Getenv("WUKONG_STORAGE_ENGINE") //默认从环境变量中 加载存储引擎
if wse == "" {
wse = DEFAULT_STORAGE_ENGINE
}
//从引擎map中获取 引擎对象
if fn, has := supportedStorage[wse]; has {
return fn(path)
}
return nil, fmt.Errorf("unsupported storage engine %v", wse)
}