Files
tplate/tool/tool.go
2025-09-19 22:05:08 +08:00

75 lines
2.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package tool
import (
"html/template"
"log"
"net/http"
"os"
"strings"
"tplate/tool/yaml"
)
func MainHandler(w http.ResponseWriter, r *http.Request) {
// 每次都读取模板文件
tmpl, err := template.ParseFiles("templates/index.tmpl")
if err != nil {
http.Error(w, "模板解析错误\n"+err.Error(), http.StatusInternalServerError)
return
}
var page SiteConfig
err = yaml.LoadYAML("config.yaml", &page)
if err != nil {
http.Error(w, "无法读取 config.yaml 数据\n"+err.Error(), http.StatusInternalServerError)
return
}
// 遍历读取 static 目录下的所有 css 文件,将目录组合成 link tag并添加到 page.Styles 中
files, err := os.ReadDir("assets")
if err != nil {
http.Error(w, "无法读取 assets 目录\n"+err.Error(), http.StatusInternalServerError)
return
}
for _, file := range files {
if file.IsDir() || !strings.HasSuffix(file.Name(), ".css") {
continue
}
page.Styles += template.HTML(`<link rel="stylesheet" media=print href="/assets/` + file.Name() + `">`)
}
// 遍历 posts/ 目录下的 .yaml 文件
files, err = os.ReadDir("images")
if err != nil {
http.Error(w, "无法读取 images 目录\n"+err.Error(), http.StatusInternalServerError)
return
}
for _, file := range files {
if file.IsDir() {
continue
}
// img, err := os.Open("./images/" + file.Name())
// if err != nil {
// http.Error(w, "无法读取图片文件\n"+err.Error(), http.StatusInternalServerError)
// return
// }
// imgdata, _, err := image.Decode(img)
// if err != nil {
// http.Error(w, "无法解码图片文件\n"+err.Error(), http.StatusInternalServerError)
// return
// }
// page.Images += template.HTML(fmt.Sprintf(`<div class="item" height="%d"><img src="/images/%s"></div>`, imgdata.Bounds().Dy(), file.Name()))
// page.Images += template.HTML(fmt.Sprintf("<div class=\"item\"><img src=\"/images/%s\"></div>", file.Name()))
page.ImageURL = append(page.ImageURL, "/images/" + file.Name())
}
err = tmpl.Execute(w, page)
if err != nil {
http.Error(w, "模板渲染错误\n"+err.Error(), http.StatusInternalServerError)
} else {
log.Println("已重载")
}
}