package models_pages 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 ( allPosts = posts{} ) func init() { if err := loadPosts(models.Cfg.PostsDir); err != nil { log.Fatalf("%v", err) } } 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 }