template_handler.go 897 B

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