当前端请求的数据通过form表单提交时,例如向/user/search发送一个POST请求,获取请求数据的方式如下:
main.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.LoadHTMLFiles("./login.html", "./index.html")
r.GET("/login", func(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
})
r.POST("/login", func(c *gin.Context) {
//方法1 用PostForm获取form表达
// username := c.PostForm("username")
// password := c.PostForm("password")
//方法2 用DefaultPostForm获取form表达,有个默认值
// username := c.DefaultPostForm("username", "默认名字")
// password := c.DefaultPostForm("password", "默认密码")
//方法3 GetPostForm 多了一个是否存在的返回值
username, ok := c.GetPostForm("username")
if !ok {
username = "默认用户名"
}
password, ok := c.GetPostForm("password")
if !ok {
password = "默认密码"
}
c.HTML(http.StatusOK, "index.html", gin.H{
"name": username,
"Password": password,
})
})
r.Run(":9090")
}
login.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>index</title>
</head>
<body>
<p>你的名字是:{{ .name }}</p>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>index</title>
</head>
<body>
<p>你的名字是:{{ .name }}</p>
</body>
</html>
编译后页面
初期进行get请求
输入用户名密码,点击登录,进行post请求