bit4sat/storage/storage.go

84 lines
1.3 KiB
Go
Raw Normal View History

2019-03-15 18:00:35 +00:00
package storage
import (
2019-03-21 17:56:35 +00:00
"errors"
"fmt"
2019-03-21 17:44:40 +00:00
"io"
2019-03-15 18:00:35 +00:00
"log"
2019-03-21 17:44:40 +00:00
"mime/multipart"
2019-03-15 18:00:35 +00:00
"os"
2019-03-21 17:44:40 +00:00
"path/filepath"
2019-03-15 18:00:35 +00:00
2019-03-23 18:29:48 +00:00
"git.sp4ke.com/sp4ke/bit4sat/utils"
2019-03-15 18:00:35 +00:00
)
const (
2019-03-21 17:44:40 +00:00
StoragePath = "file-storage"
2019-03-15 18:00:35 +00:00
StoragePathEnv = "BIT4SAT_STORAGE_PATH"
)
2019-03-21 17:44:40 +00:00
var (
RuntimeStoragePath string
)
func GetStoreDestination(filename string) string {
return filepath.Join(RuntimeStoragePath, filename)
}
func StoreFormFile(src multipart.File, filename string) error {
2019-03-21 17:56:35 +00:00
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)
2019-03-21 17:44:40 +00:00
defer fd.Close()
if err != nil {
return err
}
src.Seek(0, 0)
_, err = io.Copy(fd, src)
return err
}
2019-03-21 17:56:35 +00:00
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
}
2019-03-15 18:00:35 +00:00
func init() {
path, set := os.LookupEnv(StoragePathEnv)
if !set {
path = StoragePath
}
2019-03-21 17:44:40 +00:00
RuntimeStoragePath = path
2019-03-15 18:00:35 +00:00
err := utils.Mkdir(path)
if err != nil {
log.Fatal(err)
}
}