对于表单form都不陌生,GO是如何处理表单的呢?
先写个例子:html
<html> <head> <title></title> </head> <body> <form action="/login" method="post"> 用户名:<input type="text" name="username"> 密码:<input type="password" name="password"> <input type="submit" value="登录"> </form> </body> </html>
文件命名为login.gtpl
(与html无异)
紧接着,须要有http服务浏览器
package main import ( "fmt" "html/template" "log" "net/http" "strings" ) func login(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) //获取请求的方法 if r.Method == "GET" { t, _ := template.ParseFiles("login.gtpl") t.Execute(w, nil) } else { r.ParseForm() //请求的是登录数据,那么执行登录的逻辑判断 fmt.Println("username:", r.Form["username"]) fmt.Println("password:", r.Form["password"]) } } func main() { http.HandleFunc("/login", login) //设置访问的路由 err := http.ListenAndServe(":9090", nil) //设置监听的端口 if err != nil { log.Fatal("ListenAndServe: ", err) } }
这就写好了一个可以完成登录操做的功能。
用户访问http://domain:9090/login
便可看到登录界面。紧接着输入用户名和密码便可完成登录。
中间都发生了什么事情呢?dom
这就是请求的过程。以后是响应过程post
r.Method
拿到请求的方法template.ParseFiles("login.gtpl")
。而且将模板响应(w)t.Execute(w, nil)
给客户端,浏览器上显示登录界面。action="/login"
。r.ParseForm()
而且将相关信息打印出来。这里须要注意的一点是。Handler是不会自动解析表单的,须要显示的调用r.ParseForm()
。才能对表单执行操做r.Form["username"]
request.Form
是一个url.Values
类型,里面存储的是对应的相似key=value
的信息
另外Request
自己提供了FormValue()
来获取用户提供的参数。如r.Form["username"]
也可写成r.FormValue("username")
。调用r.FormValue
时会自动调用r.ParseForm
,因此没必要提早调用。url