ParseForm
填充r.Form和r.PostForm。For all requests,
ParseForm
parses the raw query from the URL 和 updates r.Form.用户提交的表单详细信息存储在2个变量名称和地址中。
HTML表单有2个输入框的名称和地址。
创建两个不同的文件 form.html 和 main.go
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <div> <form method="POST" action="/"> <label>Name</label><input name="name" type="text" value="" /> <label>Address</label><input name="address" type="text" value="" /> <input type="submit" value="submit" /> </form> </div> </body> </html>
package main import ( "fmt" "log" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "404 not found.", http.StatusNotFound) return } switch r.Method { case "GET": http.ServeFile(w, r, "form.html") case "POST": // Call ParseForm() to parse the raw query 和 update r.PostForm 和 r.Form. if err := r.ParseForm(); err != nil { fmt.Fprintf(w, "ParseForm() err: %v", err) return } fmt.Fprintf(w, "Post from website! r.PostFrom = %v\n", r.PostForm) name := r.FormValue("name") address := r.FormValue("address") fmt.Fprintf(w, "Name = %s\n", name) fmt.Fprintf(w, "Address = %s\n", address) default: fmt.Fprintf(w, "Sorry, only GET 和 POST methods are supported.") } } func main() { http.HandleFunc("/", hello) fmt.Printf("Starting server for testing HTTP POST...\n") if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal(err) } }
Run url
http://localhost:8080/
in your browser 和 see the below content
提交表格后
