package Helper
|
|
|
|
import (
|
|
"io"
|
|
"io/ioutil"
|
|
"mime/multipart"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"PersonalWebsite/Variables"
|
|
)
|
|
|
|
func UploadFiles(files []*multipart.FileHeader) error {
|
|
var (
|
|
file multipart.File
|
|
dst *os.File
|
|
e error
|
|
)
|
|
|
|
for i := range files {
|
|
//for each fileheader, get a handle to the actual file
|
|
file, e = files[i].Open()
|
|
defer file.Close()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
|
|
//create destination file making sure the path is writeable.
|
|
dst, e = os.Create(Variables.ProjectRoot + "/web/static/" + files[i].Filename)
|
|
defer dst.Close()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
|
|
//copy the uploaded file to the destination file
|
|
if _, e := io.Copy(dst, file); e != nil {
|
|
return e
|
|
}
|
|
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func WriteBody(title string, body string) (string, error) {
|
|
var (
|
|
filename, path string
|
|
f *os.File
|
|
e error
|
|
)
|
|
|
|
filename = strings.ReplaceAll(title, " ", "_") + ".gohtml"
|
|
|
|
path = filepath.Join(
|
|
Variables.ProjectRoot,
|
|
"web/posts/",
|
|
filename,
|
|
)
|
|
|
|
f, e = os.Create(path)
|
|
|
|
if e != nil {
|
|
return "", e
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
_, e = f.WriteString(body)
|
|
|
|
if e != nil {
|
|
return "", e
|
|
}
|
|
|
|
return filename, nil
|
|
}
|
|
|
|
func GetFileContents(path string) (string, error) {
|
|
var (
|
|
content []byte
|
|
e error
|
|
)
|
|
|
|
path = filepath.Join(
|
|
Variables.ProjectRoot,
|
|
"web/posts/",
|
|
path,
|
|
)
|
|
|
|
content, e = ioutil.ReadFile(path)
|
|
if e != nil {
|
|
return "", e
|
|
}
|
|
|
|
// Convert []byte to string and print to screen
|
|
return string(content), nil
|
|
}
|
|
|
|
func DeleteOldPostFile(title string) error {
|
|
var (
|
|
filename, path string
|
|
e error
|
|
)
|
|
|
|
filename = strings.ReplaceAll(title, " ", "_") + ".gohtml"
|
|
|
|
path = filepath.Join(
|
|
Variables.ProjectRoot,
|
|
"web/posts/",
|
|
filename,
|
|
)
|
|
|
|
e = os.Remove(path)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
|
|
return nil
|
|
}
|