hikan.ru/mvc/models/pages/posts.go

84 lines
1.4 KiB
Go

package models
import (
"bytes"
"fmt"
"html/template"
"io"
"log"
"main/mvc/models"
"main/tools"
"os"
"path/filepath"
"strings"
"time"
)
const (
// Имя соответствующего шаблона
PostsPageTmplName = "posts.gohtml"
)
type Posts map[PostLink]*Post
var (
posts = Posts{}
)
func init() {
if err := LoadPosts(models.Cfg.PostsDir); err != nil {
log.Fatalf("%v", err)
}
}
func GetPosts() Posts {
return posts
}
func LoadPosts(dir string) error {
err := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
if err != nil {
return err
}
if !f.IsDir() && strings.HasSuffix(f.Name(), ".md") {
file, err := os.Open(path)
if err != nil {
return err
}
md, err := io.ReadAll(file)
if err != nil {
return err
}
html := tools.MdToHTML(md)
link := fmt.Sprintf("/%s/", strings.TrimSuffix(filepath.Base(path), ".md"))
posts[PostLink(link)] = NewPost(link, html)
}
return nil
})
if err != nil {
return err
}
return nil
}
func RenderPostsPage(templates *template.Template, version int64) ([]byte, error) {
var pageData bytes.Buffer
context := map[string]any{
"version": version,
"renderingTimestamp": time.Now().Unix(),
"posts": posts,
}
if err := templates.ExecuteTemplate(&pageData, PostsPageTmplName, context); err != nil {
return nil, err
}
return pageData.Bytes(), nil
}