79 lines
1.9 KiB
Go
79 lines
1.9 KiB
Go
package store
|
|
|
|
import (
|
|
"io"
|
|
"log/slog"
|
|
"mime/multipart"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
func SetupStore() {
|
|
path, err := filepath.Abs(viper.GetString("store.path"))
|
|
if err != nil {
|
|
slog.Error("could get full create storage path", "error", err, "path", viper.GetString("store.path"))
|
|
panic(err)
|
|
}
|
|
err = os.MkdirAll(path, os.ModePerm)
|
|
if err != nil {
|
|
slog.Error("could get create storage directory", "error", err, "path", viper.GetString("store.path"))
|
|
}
|
|
slog.Info("Initialized File storage directory")
|
|
}
|
|
|
|
func SaveFile(file multipart.File) (string, error) {
|
|
path, err := filepath.Abs(viper.GetString("store.path"))
|
|
if err != nil {
|
|
slog.Error("could not save file,", "error", err)
|
|
return "", err
|
|
}
|
|
fileName, err := uuid.NewRandom()
|
|
if err != nil {
|
|
slog.Error("could not save file,", "error", err)
|
|
return "", err
|
|
}
|
|
osFile, err := os.Create(filepath.Join(path, fileName.String()))
|
|
if err != nil {
|
|
slog.Error("could not write to file on disk,", "error", err)
|
|
return "", err
|
|
}
|
|
_, err = io.Copy(osFile, file)
|
|
if err != nil {
|
|
slog.Error("could not save file,", "error", err)
|
|
return "", err
|
|
}
|
|
|
|
return fileName.String(), nil
|
|
}
|
|
|
|
func OpenFile(fileId string) (*os.File, error) {
|
|
path, err := filepath.Abs(viper.GetString("store.path"))
|
|
if err != nil {
|
|
slog.Error("Storage directory not accessible", "error", err)
|
|
return nil, err
|
|
}
|
|
file, err := os.Open(filepath.Join(path, fileId))
|
|
|
|
return file, err
|
|
}
|
|
|
|
func DeleteFile(fileId string) error {
|
|
path, err := filepath.Abs(viper.GetString("store.path"))
|
|
if err != nil {
|
|
slog.Error("Storage directory not accessible", "error", err)
|
|
return err
|
|
}
|
|
return os.Remove(path)
|
|
}
|
|
|
|
func absPath(fileID string) (string, error) {
|
|
path, err := filepath.Abs(viper.GetString("store.path"))
|
|
if err != nil {
|
|
slog.Error("could not get full path for file,", "error", err)
|
|
return "", err
|
|
}
|
|
return path, nil
|
|
}
|