storage.go 830 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package storage
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. const DEFAULT_STORAGE_ENGINE = "bolt"
  7. var supportedStorage = map[string]func(path string) (Storage, error){
  8. "kv": openKVStorage,
  9. "bolt": openBoltStorage,
  10. }
  11. func RegisterStorageEngine(name string, fn func(path string) (Storage, error)) {
  12. supportedStorage[name] = fn
  13. }
  14. type Storage interface {
  15. Set(k, v []byte) error
  16. Get(k []byte) ([]byte, error)
  17. Delete(k []byte) error
  18. ForEach(fn func(k, v []byte) error) error
  19. Close() error
  20. WALName() string
  21. }
  22. func OpenStorage(path string, engine string) (Storage, error) {
  23. if len(engine) <= 0 {
  24. engine = os.Getenv("WUKONG_STORAGE_ENGINE")
  25. if engine == "" {
  26. engine = DEFAULT_STORAGE_ENGINE
  27. }
  28. }
  29. if fn, has := supportedStorage[engine]; has {
  30. return fn(path)
  31. }
  32. return nil, fmt.Errorf("unsupported storage engine %v", engine)
  33. }