package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"github.com/88250/lute"
"gopkg.in/yaml.v3"
)
type BlogData struct {
Title string `yaml:"Title"`
Author string `yaml:"Author"`
Content template.HTML `yaml:"Content"`
}
func LoadYAML(pathToFile string, out interface{}) error {
file, err := os.ReadFile(pathToFile)
if err != nil {
return fmt.Errorf("读取文件失败: %w", err)
}
if err := yaml.Unmarshal(file, out); err != nil {
return fmt.Errorf("解析 YAML 失败: %w", err)
}
return nil
}
func luteHandler() string {
luteEngine := lute.New()
var privateParseOptions LuteParseOptions
LoadYAML("config/luteParse.yaml", &privateParseOptions)
luteEngine.ParseOptions = privateParseOptions.toLuteParseOptions()
var privateRenderOptions LuteRenderOptions
LoadYAML("config/luteRender.yaml", &privateRenderOptions)
luteEngine.RenderOptions = privateRenderOptions.toLuteRenderOptions()
file, err := os.ReadFile("post.md")
if err != nil {
log.Println("读取文件失败:", err)
}
return luteEngine.Md2HTML(string(file))
}
func handler(w http.ResponseWriter, r *http.Request) {
// 每次都读取模板文件
tmpl, err := template.ParseFiles("templates/index.tmpl")
if err != nil {
http.Error(w, "模板解析错误", http.StatusInternalServerError)
return
}
var post BlogData
err = LoadYAML("config/siteInfo.yaml", &post)
if err != nil {
http.Error(w, "无法读取数据", http.StatusInternalServerError)
return
}
post.Content = template.HTML(luteHandler())
err = tmpl.Execute(w, post)
if err != nil {
http.Error(w, "模板渲染错误", http.StatusInternalServerError)
}
}
func main() {
http.HandleFunc("/", handler)
log.Println("服务器启动,访问 http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}