-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog.go
78 lines (64 loc) · 1.77 KB
/
blog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package handlers
import (
"fmt"
"html/template"
"net/http"
"os"
"github.com/go-chi/chi/v5"
"github.com/nickfoden/web-log/internal/models"
)
type BlogHandler struct {
posts []models.Post
}
func renderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
// Parse the base template and the child template
t, err := template.ParseFiles(
"internal/templates/base.html",
"internal/templates/"+tmpl,
)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
// Execute the template with the data
err = t.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func NewBlogHandler(posts []models.Post) *BlogHandler {
return &BlogHandler{posts: posts}
}
func (h *BlogHandler) Index(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "index.html", map[string]interface{}{
"Title": "Web Log by Nick Foden",
"Posts": h.posts,
})
}
func (h *BlogHandler) About(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "about.html", map[string]interface{}{
"Title": "Web Log by Nick Foden",
})
}
func (h *BlogHandler) Post(w http.ResponseWriter, r *http.Request) {
slug := chi.URLParam(r, "slug")
for _, post := range h.posts {
if post.Slug == slug {
content, err := os.ReadFile(fmt.Sprintf("internal/content/posts/%s.html", post.Slug))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
renderTemplate(w, "post.html", map[string]interface{}{
"Content": template.HTML(content),
"Title": "Web Log by Nick Foden",
"Post": post,
})
return
}
}
http.NotFound(w, r)
}