添加模版
{{if .Success}}
<h1>Thanks for your message!</h1>
<label>Email:</label><br />
<label>{{.Details.Email}}</label><br />
<label>Subject:</label><br />
<label>{{.Details.Subject}}</label><br />
<label>Message:</label><br />
<label>{{.Details.Message}}</label>
{{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}}
读取模版
tmpl := template.Must(template.ParseFiles("forms.html"))
响应请求
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"),
}
tmpl.Execute(w, struct {
Success bool
Details ContactDetails
}{true, details})
}
该响应方法中,先判断请求是否为post,如果不是,响应体写入模版并填入空数据;如果是,响应体写入模版并填入提交的数据。
完整代码
package main
import (
"fmt"
"html/template"
"net/http"
)
type ContactDetails struct {
Email string
Subject string
Message string
}
func main() {
tmpl := template.Must(template.ParseFiles("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"),
}
fmt.Println(details)
tmpl.Execute(w, struct {
Success bool
Details ContactDetails
}{true, details})
})
http.ListenAndServe(":8090", nil)
}
打开浏览器并访问链接:http://localhost:8090/
填入数据并提交: