76 lines
1.3 KiB
Go
76 lines
1.3 KiB
Go
package models_pages
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
"main/tools"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
// Имя соответствующего шаблона
|
|
PostsPageTmplName = "posts.gohtml"
|
|
)
|
|
|
|
type posts map[PostLink]*Post
|
|
|
|
var (
|
|
allPosts = posts{}
|
|
)
|
|
|
|
func GetPosts() posts {
|
|
return allPosts
|
|
}
|
|
|
|
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"))
|
|
allPosts[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": allPosts,
|
|
}
|
|
|
|
if err := templates.ExecuteTemplate(&pageData, PostsPageTmplName, context); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return pageData.Bytes(), nil
|
|
}
|