go提供html/template用于解析html模板文件,将模板文件提交的输入转换成结构体并用于渲染。
package main
import (
"html/template"
"net/http"
)
type ContactDetails struct {
Email string
Subject string
Message string
}
func main() {
tmpl := template.Must(template.ParseFiles("H:\\go\\main\\forms.html"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
tmpl.Execute(w, nil)
return
}
details := ContactDetails{
Email: r.FormValue("email"),
Subject: r.FormValue("subject"),
Message: r.FormValue("message"),
}
// do something with details
_ = details
tmpl.Execute(w, struct {Success bool}{true})
})
http.ListenAndServe(":8080", nil)
}
html模板文件内容:
<!DOCTYPE html>
{{if .Success}}
<h1>Thanks for your message!</h1>
{{else}}
<h1>Contact</h1>
<form method="POST">
<label>Email:</label><br />
<input type="text" name="email"><br />
<label>Subject:</label><br />
<input type="text" name="subject"><br />
<label>Message:</label><br />
<textarea name="message"></textarea><br />
<input type="submit">
</form>
{{end}}
启动项目,访问http://8080端口

随意输入,点击提交输出显示成功的信息。

Go语言模板引擎实践
本文介绍如何使用Go语言中的html/template包来实现简单的表单处理功能。通过一个具体的例子展示了如何解析HTML模板文件并将表单数据渲染到网页上。
3031

被折叠的 条评论
为什么被折叠?



