forked from FabianVowie/Lithium
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.0 KiB
75 lines
2.0 KiB
package storage
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/spf13/afero"
|
|
)
|
|
|
|
const StorageFolderName = "files"
|
|
|
|
type IStorageProvider interface {
|
|
StoreRaw(bucketName string, objectName string, data []byte) (string, error)
|
|
StoreExisting(bucketName string, objectName string, existingFilePath string) (string, error)
|
|
GetPath(bucketName string, objectName string) string
|
|
}
|
|
|
|
type FileSystemStorageProvider struct {
|
|
fileSystem afero.Fs
|
|
basePath string
|
|
wd string
|
|
}
|
|
|
|
func (sp FileSystemStorageProvider) StoreRaw(bucketName string, objectName string, data []byte) (string, error) {
|
|
directoryPath := filepath.Join(sp.basePath, bucketName)
|
|
|
|
if err := sp.fileSystem.MkdirAll(directoryPath, os.ModePerm); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
filePath := filepath.Join(directoryPath, objectName)
|
|
|
|
if err := afero.WriteFile(sp.fileSystem, filePath, data, os.ModePerm); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return filePath, nil
|
|
}
|
|
|
|
func (sp FileSystemStorageProvider) StoreExisting(bucketName string, objectName string, existingFilePath string) (string, error) {
|
|
bytesRead, err := os.ReadFile(existingFilePath)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return sp.StoreRaw(bucketName, objectName, bytesRead)
|
|
}
|
|
|
|
func (sp FileSystemStorageProvider) GetPath(bucketName string, objectName string) string {
|
|
return filepath.Join(sp.wd, StorageFolderName, sp.basePath, bucketName, objectName)
|
|
}
|
|
|
|
func (sp FileSystemStorageProvider) OpenFile(bucketName string, objectName string) (*os.File, error) {
|
|
return os.Open(sp.GetPath(bucketName, objectName))
|
|
}
|
|
|
|
func GetFileSystemStorageProvider(basePath string, wd string) FileSystemStorageProvider {
|
|
if wd == "" {
|
|
wd, _ = os.Getwd()
|
|
}
|
|
|
|
return FileSystemStorageProvider{
|
|
fileSystem: afero.NewBasePathFs(afero.NewOsFs(), filepath.Join(wd, StorageFolderName)),
|
|
basePath: basePath,
|
|
wd: wd,
|
|
}
|
|
}
|
|
|
|
// TODO: Move this out of this file
|
|
func GetMemoryStorageProvider() FileSystemStorageProvider {
|
|
return FileSystemStorageProvider{
|
|
fileSystem: afero.NewBasePathFs(afero.NewMemMapFs(), "/"),
|
|
basePath: "/tmp/foo/bar",
|
|
}
|
|
}
|