feat: add folders utils

This commit is contained in:
Yanislav Igonin 2021-09-04 21:53:48 +03:00
parent cc5ded555a
commit 8708374f64
2 changed files with 54 additions and 1 deletions

View File

@ -11,7 +11,7 @@ import (
Controllers "micrach/controllers" Controllers "micrach/controllers"
Db "micrach/db" Db "micrach/db"
Repositories "micrach/repositories" Repositories "micrach/repositories"
// Utils "micrach/utils" Utils "micrach/utils"
) )
func main() { func main() {
@ -21,6 +21,11 @@ func main() {
gin.SetMode(Config.App.Env) gin.SetMode(Config.App.Env)
Repositories.Seed() Repositories.Seed()
err := Utils.CreateUploadsFolder()
if err != nil {
log.Panicln(err)
}
router := gin.Default() router := gin.Default()
router.LoadHTMLGlob("templates/*.html") router.LoadHTMLGlob("templates/*.html")
router.Static("/uploads", "./uploads") router.Static("/uploads", "./uploads")

48
utils/utils.go Normal file
View File

@ -0,0 +1,48 @@
package utils
import (
"errors"
"os"
"path/filepath"
"strconv"
)
var UPLOADS_DIR_PATH = "uploads"
// Check dir existence.
func CheckIfFolderExists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
// Creates folder for uploads.
func CreateUploadsFolder() error {
isExists := CheckIfFolderExists(UPLOADS_DIR_PATH)
if isExists {
return nil
}
err := os.Mkdir(UPLOADS_DIR_PATH, 0755)
if err != nil {
return err
}
return nil
}
// Creates folder for thread.
func CreateThreadFolder(postID int) error {
threadDirPath := filepath.Join(UPLOADS_DIR_PATH, strconv.Itoa(postID))
isExists := CheckIfFolderExists(threadDirPath)
if isExists {
return errors.New("folder already exists")
}
err := os.Mkdir(threadDirPath, 0755)
if err != nil {
return err
}
return nil
}