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.

116 lines
1.6 KiB

  1. package helper
  2. import (
  3. "io"
  4. "io/ioutil"
  5. "mime/multipart"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "git.tovijaeschke.xyz/tovi/personal_website/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. file, e = files[i].Open()
  19. defer file.Close()
  20. if e != nil {
  21. return e
  22. }
  23. dst, e = os.Create(variables.ProjectRoot + "/web/static/" + files[i].Filename)
  24. defer dst.Close()
  25. if e != nil {
  26. return e
  27. }
  28. if _, e := io.Copy(dst, file); e != nil {
  29. return e
  30. }
  31. }
  32. return nil
  33. }
  34. func WriteBody(title string, body string) (string, error) {
  35. var (
  36. filename, path string
  37. f *os.File
  38. e error
  39. )
  40. filename = strings.ReplaceAll(title, " ", "_") + ".gohtml"
  41. path = filepath.Join(
  42. variables.ProjectRoot,
  43. "web/posts/",
  44. filename,
  45. )
  46. f, e = os.Create(path)
  47. if e != nil {
  48. return "", e
  49. }
  50. defer f.Close()
  51. _, e = f.WriteString(body)
  52. if e != nil {
  53. return "", e
  54. }
  55. return filename, nil
  56. }
  57. func GetFileContents(path string) (string, error) {
  58. var (
  59. content []byte
  60. e error
  61. )
  62. path = filepath.Join(
  63. variables.ProjectRoot,
  64. "web/posts/",
  65. path,
  66. )
  67. content, e = ioutil.ReadFile(path)
  68. if e != nil {
  69. return "", e
  70. }
  71. // Convert []byte to string and print to screen
  72. return string(content), nil
  73. }
  74. func DeleteOldPostFile(title string) error {
  75. var (
  76. filename, path string
  77. e error
  78. )
  79. filename = strings.ReplaceAll(title, " ", "_") + ".gohtml"
  80. path = filepath.Join(
  81. variables.ProjectRoot,
  82. "web/posts/",
  83. filename,
  84. )
  85. e = os.Remove(path)
  86. if e != nil {
  87. return e
  88. }
  89. return nil
  90. }