atri.dad/pages/posts.go

72 lines
1.5 KiB
Go
Raw Normal View History

2023-05-18 20:04:55 -06:00
package pages
import (
"io/fs"
"log"
"net/http"
"sort"
"strings"
"time"
contentfs "atri.dad/content"
"atri.dad/lib"
"github.com/labstack/echo/v4"
)
2024-08-21 12:59:22 -06:00
type PostsProps struct {
2023-05-18 20:04:55 -06:00
Posts []lib.CardLink
}
2024-08-21 12:59:22 -06:00
func Posts(c echo.Context) error {
2023-05-18 20:04:55 -06:00
var posts []lib.CardLink
files, err := fs.ReadDir(contentfs.FS, ".")
if err != nil {
2024-05-08 14:43:57 -06:00
lib.LogError.Println(err)
2023-05-18 20:04:55 -06:00
http.Error(c.Response().Writer, "There was an issue finding posts!", http.StatusInternalServerError)
return nil
}
for _, file := range files {
if !file.IsDir() && strings.HasSuffix(file.Name(), ".md") {
frontMatter, err := lib.ExtractFrontMatter(file, contentfs.FS)
if err != nil {
2024-05-08 14:43:57 -06:00
lib.LogError.Println(err)
2023-05-18 20:04:55 -06:00
http.Error(c.Response().Writer, "There was an issue rendering the posts!", http.StatusInternalServerError)
return nil
}
2024-08-21 12:59:22 -06:00
frontMatter.Href = "posts/" + strings.TrimSuffix(file.Name(), ".md")
2023-05-18 20:04:55 -06:00
frontMatter.Internal = true
posts = append(posts, frontMatter)
}
}
const layout = "January 2 2006"
sort.Slice(posts, func(i, j int) bool {
iDate, err := time.Parse(layout, posts[i].Date)
if err != nil {
log.Fatal(err)
}
jDate, err := time.Parse(layout, posts[j].Date)
if err != nil {
log.Fatal(err)
}
return iDate.Before(jDate)
})
2024-08-21 12:59:22 -06:00
props := PostsProps{
2023-05-18 20:04:55 -06:00
Posts: posts,
}
// Specify the partials used by this page
partials := []string{"header", "navitems", "cardlinks"}
// Render the template
return lib.RenderTemplate(c.Response().Writer, "base", partials, props)
}