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

96 lines
1.5 KiB

  1. package Helper
  2. import (
  3. "io"
  4. "io/ioutil"
  5. "mime/multipart"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "PersonalWebsite/Variables"
  10. )
  11. func UploadFiles(files []*multipart.FileHeader) error {
  12. var (
  13. file multipart.File
  14. dst *os.File
  15. e error
  16. )
  17. for i := range files {
  18. //for each fileheader, get a handle to the actual file
  19. file, e = files[i].Open()
  20. defer file.Close()
  21. if e != nil {
  22. return e
  23. }
  24. //create destination file making sure the path is writeable.
  25. dst, e = os.Create(Variables.ProjectRoot + "/web/static/" + files[i].Filename)
  26. defer dst.Close()
  27. if e != nil {
  28. return e
  29. }
  30. //copy the uploaded file to the destination file
  31. if _, e := io.Copy(dst, file); e != nil {
  32. return e
  33. }
  34. }
  35. return nil
  36. }
  37. func WriteBody(title string, body string) (string, error) {
  38. var (
  39. filename, path string
  40. f *os.File
  41. e error
  42. )
  43. filename = strings.ReplaceAll(title, " ", "_") + ".gohtml"
  44. path = filepath.Join(
  45. Variables.ProjectRoot,
  46. "web/posts/",
  47. filename,
  48. )
  49. f, e = os.Create(path)
  50. if e != nil {
  51. return "", e
  52. }
  53. defer f.Close()
  54. _, e = f.WriteString(body)
  55. if e != nil {
  56. return "", e
  57. }
  58. return filename, nil
  59. }
  60. func GetFileContents(path string) (string, error) {
  61. var (
  62. content []byte
  63. e error
  64. )
  65. path = filepath.Join(
  66. Variables.ProjectRoot,
  67. "web/posts/",
  68. path,
  69. )
  70. content, e = ioutil.ReadFile(path)
  71. if e != nil {
  72. return "", e
  73. }
  74. // Convert []byte to string and print to screen
  75. return string(content), nil
  76. }