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", "
") 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) } } }