91 lines
1.7 KiB
Go
91 lines
1.7 KiB
Go
package blog
|
|
|
|
import (
|
|
"embed"
|
|
"fmt"
|
|
"html/template"
|
|
"net/http"
|
|
"prettysunflower-website/baseTemplates"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type Post struct {
|
|
Slug string
|
|
Title string
|
|
Author string
|
|
Date time.Time
|
|
UpdatedDate time.Time
|
|
Body template.HTML
|
|
}
|
|
|
|
//go:embed posts/*
|
|
var postsFS embed.FS
|
|
|
|
func getAllPosts() []Post {
|
|
postsDir, err := postsFS.ReadDir("posts")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
var posts []Post
|
|
|
|
for _, postFileName := range postsDir {
|
|
post, err := postsFS.ReadFile(fmt.Sprint("posts/", postFileName.Name()))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
posts = append(posts, makePost(post))
|
|
}
|
|
|
|
sort.Slice(posts, func(i, j int) bool {
|
|
return posts[i].Date.After(posts[j].Date)
|
|
})
|
|
|
|
return posts
|
|
}
|
|
|
|
type PostListTemplateData struct {
|
|
Posts []Post
|
|
}
|
|
|
|
func blogTop(w http.ResponseWriter, r *http.Request) {
|
|
posts := getAllPosts()
|
|
templateData := PostListTemplateData{
|
|
Posts: posts,
|
|
}
|
|
|
|
tmpl := template.Must(template.ParseFS(baseTemplates.FS, "templates/base.tmpl", "templates/blog/postsList.tmpl"))
|
|
|
|
err := tmpl.ExecuteTemplate(w, "base", templateData)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
|
|
func showPost(w http.ResponseWriter, r *http.Request) {
|
|
slug := r.PathValue("slug")
|
|
posts := getAllPosts()
|
|
postIndex, found := sort.Find(len(posts), func(i int) int {
|
|
return strings.Compare(slug, posts[i].Slug)
|
|
})
|
|
|
|
if !found {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
post := posts[postIndex]
|
|
|
|
tmpl := template.Must(template.ParseFS(baseTemplates.FS, "templates/base.tmpl", "templates/blog/blogPost.tmpl"))
|
|
|
|
err := tmpl.ExecuteTemplate(w, "base", post)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|