// Package templates 提供 HTML 模板的处理功能 package templates import ( "net/http" "path/filepath" "sync" "text/template" ) // TemplateHandler 负责处理 HTML 模板的渲染 type TemplateHandler struct { once sync.Once // 确保模板只被解析一次 Filename string // 模板文件名 templ *template.Template // 解析后的模板对象 } // ServeHTTP 处理 HTTP 请求并渲染模板 // 实现了 http.Handler 接口 func (t *TemplateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // 使用 sync.Once 确保模板只被解析一次,避免重复解析带来的性能开销 t.once.Do(func() { // 解析模板文件,如果失败会 panic t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.Filename))) }) // 执行模板渲染,将请求对象作为数据传递给模板 t.templ.Execute(w, r) }