pasty/internal/storage/driver.go

58 lines
1.2 KiB
Go
Raw Normal View History

2020-08-23 01:06:29 +03:00
package storage
import (
"fmt"
"strings"
2021-04-15 20:26:17 +03:00
"github.com/lus/pasty/internal/env"
"github.com/lus/pasty/internal/pastes"
2020-08-23 01:06:29 +03:00
)
// Current holds the current storage driver
var Current Driver
// Driver represents a storage driver
type Driver interface {
Initialize() error
Terminate() error
ListIDs() ([]string, error)
Get(id string) (*pastes.Paste, error)
2020-08-23 01:06:29 +03:00
Save(paste *pastes.Paste) error
Delete(id string) error
2020-09-19 02:56:50 +03:00
Cleanup() (int, error)
2020-08-23 01:06:29 +03:00
}
// Load loads the current storage driver
func Load() error {
2020-08-24 00:44:47 +03:00
// Define the driver to use
2020-08-26 23:12:36 +03:00
storageType := env.Get("STORAGE_TYPE", "file")
driver, err := GetDriver(storageType)
if err != nil {
return err
2020-08-23 01:06:29 +03:00
}
2020-08-24 00:44:47 +03:00
// Initialize the driver
2020-08-26 23:12:36 +03:00
err = driver.Initialize()
2020-08-24 00:44:47 +03:00
if err != nil {
return err
}
Current = driver
return nil
2020-08-23 01:06:29 +03:00
}
2020-08-26 23:12:36 +03:00
// GetDriver returns the driver with the given type string if it exists
func GetDriver(storageType string) (Driver, error) {
switch strings.ToLower(storageType) {
case "file":
return new(FileDriver), nil
case "s3":
return new(S3Driver), nil
case "mongodb":
return new(MongoDBDriver), nil
2020-08-28 20:55:10 +03:00
case "sql":
return new(SQLDriver), nil
2020-08-26 23:12:36 +03:00
default:
return nil, fmt.Errorf("invalid storage type '%s'", storageType)
}
}