Added blog posts, and improved homepage
This commit is contained in:
87
blog/posts.go
Normal file
87
blog/posts.go
Normal file
@@ -0,0 +1,87 @@
|
||||
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))
|
||||
}
|
||||
|
||||
//fmt.Println(posts[0].UpdatedDate.IsZero())
|
||||
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
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user