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.

82 lines
1.7 KiB

  1. package webserver
  2. import (
  3. "log"
  4. "net/http"
  5. "path"
  6. "text/template"
  7. "git.tovijaeschke.xyz/tovi/personal_website/database"
  8. "git.tovijaeschke.xyz/tovi/personal_website/helper"
  9. )
  10. type Unauthenticated struct {
  11. FlashMsg string
  12. }
  13. var (
  14. partials = []string{
  15. "html/header.gohtml",
  16. "html/sidebar.gohtml",
  17. "html/index-intro.gohtml",
  18. "html/index-links.gohtml",
  19. "html/index-post-list.gohtml",
  20. "html/post-list.gohtml",
  21. "html/post.gohtml",
  22. "html/error.gohtml",
  23. }
  24. )
  25. func ServeTemplate(w http.ResponseWriter, r *http.Request, mainFile string, v map[string]interface{}) {
  26. var (
  27. tpl *template.Template
  28. files []string
  29. e error
  30. )
  31. if _, ok := v["Subject"]; !ok {
  32. v["Subject"] = ""
  33. }
  34. v["LastUpdatedAt"], e = database.GetLastUpdatedAt()
  35. if e != nil {
  36. v["LastUpdatedAt"] = " - "
  37. }
  38. v["SidebarLinks"], e = database.GetAllSidebarLinks()
  39. if e != nil {
  40. log.Println(e)
  41. http.Redirect(w, r, "/error", 302)
  42. return
  43. }
  44. files = []string{webRootJoin(mainFile)}
  45. for _, p := range partials {
  46. files = append(files, webRootJoin(p))
  47. }
  48. tpl, e = template.New(path.Base(files[0])).Funcs(
  49. template.FuncMap{
  50. "FormatTimestamp": helper.FormatTimestamp,
  51. "MinusInt64": helper.MinusInt64,
  52. "MinusInt": helper.MinusInt,
  53. "Minus": helper.MinusInt,
  54. "PlusInt64": helper.PlusInt64,
  55. "PlusInt": helper.PlusInt,
  56. "Iterate": helper.Iterate,
  57. "StrToLower": helper.StrToLower,
  58. },
  59. ).ParseFiles(files...)
  60. if e != nil {
  61. log.Println(e)
  62. http.Redirect(w, r, "/error", 302)
  63. }
  64. w.Header().Set("Content-type", "text/html")
  65. e = tpl.Execute(w, v)
  66. if e != nil {
  67. log.Println(e)
  68. http.Redirect(w, r, "/error", 302)
  69. return
  70. }
  71. }