创建表单
新增路由:
func articlesCreateHandler(w http.ResponseWriter, r *http.Request) {fmt.Fprint(w, "创建博文表单")}
添加一个处理函数:
router.HandleFunc("/articles/create",articlesCreateHandler).Methods("GET").Name("articles.create")
修改 articlesCreateHandler 函数,返回表单内容:
func articlesCreateHandler(w http.ResponseWriter, r *http.Request) {html := `<!DOCTYPE html><html lang="en"><head><title>创建文章 —— 我的技术博客</title></head><body><form action="%s" method="post"><p><input type="text" name="title"></p><p><textarea name="body" cols="30" rows="10"></textarea></p><p><button type="submit">提交</button></p></form></body></html>`storeURL, _ := router.Get("articles.store").URL()fmt.Fprintf(w, html, storeURL)}
并将 router 的声明移到包之外。注意:包级别的变量声明时不能使用 := 语法,修改为带关键词 var 的变量声明即可。
var router = mux.NewRouter()
保存后将编译成功,浏览器访问 localhost:3000/articles/create ,可以看到表单。
读取表单提交参数
修改 articlesStoreHandler() 函数,打印提交的参数:
func articlesStoreHandler(w http.ResponseWriter, r *http.Request) {err := r.ParseForm()if err != nil {// 解析错误,这里应该有错误处理fmt.Fprint(w, "请提供正确的数据!")return}title := r.PostForm.Get("title")fmt.Fprintf(w, "POST PostForm: %v <br>", r.PostForm)fmt.Fprintf(w, "POST Form: %v <br>", r.Form)fmt.Fprintf(w, "title 的值为: %v", title)}
关于错误处理,一般常见的简写是:
if err := r.ParseForm(); err != nil {// 解析错误,这里应该有错误处理fmt.Fprint(w, "请提供正确的数据!")return}
打印出来的数据可见 r.PostForm 和 r.Form 的数据是一样的。
- Form:存储了 post、put 和 get 参数,在使用之前需要调用 Form 方法。
- PostForm:存储了 post、put 参数,在使用之前需要调用 ParseForm 方法。
修改表单提交请求:
<form action="%s?test=data" method="post"><p><input type="text" name="title"></p><p><textarea name="body" cols="30" rows="10"></textarea></p><p><button type="submit">提交</button></p></form>
如不想获取所有的请求内容,而是逐个获取的话,这也是比较常见的操作,无需使用 r.ParseForm() 可直接使用 r.FormValue() 和 r.PostFormValue() 方法:
func articlesStoreHandler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "r.Form 中 title 的值为: %v <br>", r.FormValue("title"))fmt.Fprintf(w, "r.PostForm 中 title 的值为: %v <br>", r.PostFormValue("title"))fmt.Fprintf(w, "r.Form 中 test 的值为: %v <br>", r.FormValue("test"))fmt.Fprintf(w, "r.PostForm 中 test 的值为: %v <br>", r.PostFormValue("test"))}
