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(``) } // 遍历 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(`