package main import ( "bufio" "errors" "html/template" "net/http" "os" "path/filepath" "slices" "strings" "time" "github.com/adrg/frontmatter" ) type Post struct { markdownData []byte Title string `toml:"title"` PostDate time.Time `toml:"post_date"` Summary string `toml:"summary"` Body template.HTML FileName string } func postHandler(w http.ResponseWriter, r *http.Request) { if _, err := os.Stat(filepath.Join(contentDir, "posts", r.PathValue("post")+".md")); err == nil { } else if errors.Is(err, os.ErrNotExist) { sendError(w, http.StatusNotFound, "That post could not be found.") return } else { sendError(w, http.StatusInternalServerError, "There was a problem statting the file for that post: "+err.Error()) return } tmpl := template.Must(template.ParseFiles(filepath.Join(contentDir, "templates/layout.gohtml"), filepath.Join(contentDir, "templates/post.gohtml"))) f, err := os.Open(filepath.Join("posts", r.PathValue("post")+".md")) if err != nil { sendError(w, http.StatusInternalServerError, "There was a problem opening the file for that post: "+err.Error()) return } var post Post rest, err := frontmatter.Parse(bufio.NewReader(f), &post) if err != nil { sendError(w, http.StatusInternalServerError, "There was a problem reading the frontmatter for that post: "+err.Error()) return } post.FileName = r.PathValue("post") post.Body = template.HTML(mdToHTML(rest)) var data PageData = PageData{ Header: config.HeaderData, Post: post, } tmpl.ExecuteTemplate(w, "layout", data) } func blogHandler(w http.ResponseWriter, r *http.Request) { var data PageData = PageData{ Header: config.HeaderData, Posts: make([]Post, 0), } files, _ := os.ReadDir(filepath.Join(contentDir, "posts")) for _, file := range files { if strings.HasSuffix(file.Name(), ".md") { f, err := os.Open(filepath.Join(contentDir, "posts", file.Name())) if err != nil { continue } var post Post rest, err := frontmatter.Parse(bufio.NewReader(f), &post) if err != nil { continue } post.Body = template.HTML(mdToHTML(rest)) post.FileName = strings.TrimSuffix(file.Name(), ".md") data.Posts = append(data.Posts, post) } } slices.Reverse(data.Posts) tmpl := template.Must(template.ParseFiles(filepath.Join(contentDir, "templates/layout.gohtml"), filepath.Join(contentDir, "templates/blog.gohtml"))) tmpl.ExecuteTemplate(w, "layout", data) }