You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bit4sat/storage/storage.go

84 lines
1.3 KiB
Go

package storage
import (
"errors"
"fmt"
"io"
"log"
"mime/multipart"
"os"
"path/filepath"
"git.sp4ke.com/sp4ke/bit4sat/utils"
)
const (
StoragePath = "file-storage"
StoragePathEnv = "BIT4SAT_STORAGE_PATH"
)
var (
RuntimeStoragePath string
)
func GetStoreDestination(filename string) string {
return filepath.Join(RuntimeStoragePath, filename)
}
func StoreFormFile(src multipart.File, filename string) error {
filePath := GetStoreDestination(filename)
// If file exists just return
exists, err := CheckFileExists(filePath)
if err != nil {
return err
}
if exists {
log.Printf("file %s exists, skipping write", filename)
return nil
}
fd, err := os.Create(filePath)
defer fd.Close()
if err != nil {
return err
}
src.Seek(0, 0)
_, err = io.Copy(fd, src)
return err
}
func CheckFileExists(file string) (bool, error) {
info, err := os.Stat(file)
if err == nil {
if info.IsDir() {
errMsg := fmt.Sprintf("'%s' is a directory", file)
return false, errors.New(errMsg)
}
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func init() {
path, set := os.LookupEnv(StoragePathEnv)
if !set {
path = StoragePath
}
RuntimeStoragePath = path
err := utils.Mkdir(path)
if err != nil {
log.Fatal(err)
}
}