feat(web): 添加动态模板和表单编辑功能
- 新增 dynamic.go 文件处理 HTML 模板请求 - 实现模板函数 intVal用于字符串到整数转换 - 添加 edit.html 模板支持产品数据编辑- 创建 forms.go 处理表单提交和数据更新 - 新增静态文件服务支持 /static/ 路径访问 - 添加 products.html 模板显示产品列表 - 实现 JSON 数据接口 /json 返回产品列表 - 添加 Bootstrap 样式支持改善界面显示- 实现产品编辑链接和表单提交功能 - 添加输入验证和错误处理机制
This commit is contained in:
45
24-httpserver/httpserver/dynamic.go
Normal file
45
24-httpserver/httpserver/dynamic.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Context struct {
|
||||
Request *http.Request
|
||||
Data []Product
|
||||
}
|
||||
|
||||
var htmlTemplates *template.Template
|
||||
|
||||
func HandleTemplateRequest(writer http.ResponseWriter, request *http.Request) {
|
||||
path := request.URL.Path
|
||||
if path == "" {
|
||||
path = "products.html"
|
||||
}
|
||||
t := htmlTemplates.Lookup(path)
|
||||
if t == nil {
|
||||
http.NotFound(writer, request)
|
||||
return
|
||||
}
|
||||
err := t.Execute(writer, Context{request, ProductList})
|
||||
if err != nil {
|
||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
htmlTemplates = template.New("all")
|
||||
htmlTemplates.Funcs(map[string]interface{}{
|
||||
"intVal": strconv.Atoi,
|
||||
})
|
||||
htmlTemplates, err = htmlTemplates.ParseGlob("templates/*.html")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
return
|
||||
}
|
||||
http.Handle("/templates/", http.StripPrefix("/templates/", http.HandlerFunc(HandleTemplateRequest)))
|
||||
}
|
||||
Reference in New Issue
Block a user