cmd/server/genblog.go (view raw)
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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
package main
import (
"fmt"
"os"
"sort"
"strings"
"text/template"
)
type (
blogData struct {
Date string
Title string
URL string
Text string
Attachments []string
}
)
func generateBlog() {
fmt.Println("Generating blog page...")
blogDataSlice := generateBlogPage()
fmt.Println("Generating blog posts...")
generateBlogPosts(blogDataSlice)
}
func generateBlogPage() []blogData {
// open blog dir
blogDir, err := os.Open("blog")
if err != nil {
fmt.Printf("ERROR opening blog dir: %s\n", err)
}
// read blog dir list
postDirList, err := blogDir.Readdirnames(0)
if err != nil {
fmt.Printf("ERROR reading blog list: %s\n", err)
}
// sort in reverse to show latest post first
sort.Sort(sort.Reverse(sort.StringSlice(postDirList)))
var blogDataSlice []blogData
// separate date and title in struct
for _, post := range postDirList {
fmt.Println(post)
blogDataSlice = append(blogDataSlice, blogData{
Date: post[:10],
Title: post[11:],
URL: "blog/" +
strings.ToLower(strings.ReplaceAll(post, " ", "-")),
})
}
// template
tpl, err := template.ParseFiles("templates/blogposts.gotmpl")
if err != nil {
fmt.Printf("ERROR creating template: %s\n", err)
}
f, err := os.Create("html/blog.html")
if err != nil {
fmt.Printf("ERROR creating html: %s\n", err)
panic(1)
}
err = tpl.ExecuteTemplate(f, "blogposts.gotmpl", blogDataSlice)
if err != nil {
fmt.Printf("ERROR executing template: %s\n", err)
}
return blogDataSlice
}
func generateBlogPosts(blogDataSlice []blogData) {
for _, post := range blogDataSlice {
content, err := os.ReadFile(
"blog/" + post.Date + " " + post.Title + "/post.txt")
if err != nil {
fmt.Printf("ERROR reading post file: %s\n", err)
}
post.Text = string(content)
post.Text = strings.ReplaceAll(post.Text, "\n", "<br>")
tpl, err := template.ParseFiles("templates/blogpost.gotmpl")
if err != nil {
fmt.Printf("ERROR creating template: %s\n", err)
}
f, err := os.Create("html/" + post.URL + ".html")
if err != nil {
fmt.Printf("ERROR creating html: %s\n", err)
panic(1)
}
err = tpl.ExecuteTemplate(f, "blogpost.gotmpl", post)
if err != nil {
fmt.Printf("ERROR executing template: %s\n", err)
}
}
}
|