scanfile/server/internal/store/store.go

94 lines
2.5 KiB
Go

package store
import (
"fmt"
"log/slog"
"os"
"path/filepath"
"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(fileName string, fileBytes []byte) (string, error) {
path, err := filepath.Abs(viper.GetString("store.path"))
if err != nil {
slog.Error("could not save file,", "error", err, "file-uuid", fileName)
return "", err
}
osFile, err := os.Create(filepath.Join(path, fileName))
if err != nil {
slog.Error("could not create file on disk,", "error", err, "file-uuid", fileName)
return "", err
}
defer osFile.Close()
i, err := osFile.Write(fileBytes)
if err != nil {
slog.Error("could not write file content,", "error", err, "file-uuid", fileName)
return "", err
}
slog.Debug("File successfully written to disk", "size", i, "file-uuid", fileName)
return fileName, nil
}
func OpenFile(fileName string) (*os.File, error) {
path, err := filepath.Abs(viper.GetString("store.path"))
if err != nil {
slog.Error("Storage directory not accessible", "error", err, "file-uuid", fileName)
return nil, err
}
file, err := os.Open(filepath.Join(path, fileName))
return file, err
}
func DeleteFile(fileName string) error {
path, err := filepath.Abs(viper.GetString("store.path"))
if err != nil {
slog.Error("Storage directory not accessible", "error", err, "file-uuid", fileName)
return err
}
file := filepath.Join(path, fileName)
return os.Remove(file)
}
func AbsPath(fileName 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, "file-uuid", fileName)
return "", err
}
return filepath.Join(path, fileName), nil
}
func GetFileBytes(fileName string) ([]byte, error) {
var fileBytes []byte
absPath, err := AbsPath(fileName)
if err != nil {
return fileBytes, err
}
fileBytes, err = os.ReadFile(absPath)
if err != nil {
slog.Error("could not read file content,", "error", err, "file-uuid", fileName)
return fileBytes, err
}
if len(fileBytes) == 0 {
slog.Error("File is empty", "error", "Empty file", "file-uuid", fileName)
return fileBytes, fmt.Errorf("Empty file")
}
return fileBytes, nil
}