Gin框架获取form参数
Gin框架获取form参数
登录界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/login" method="post">
<div>
<label for="username">username</label>
<input type="text" name="username" id="username">
</div>
<div>
<label for="password">password</label>
<input type="password" name="password" , id="password">
</div>
<div>
<input type="submit" value="登录">
</div>
</form>
</body>
</html>
一、PostForm方式
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.LoadHTMLFiles("../templates/login.html")
// 获取form表单提交数据
r.GET("/login", func(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
})
// 获取数据
r.POST("/login", func(c *gin.Context) {
// 方式一
username := c.PostForm("username")
password := c.PostForm("password")
c.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
})
})
r.Run(":9999")
}
二、DefaultPostForm方式
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.LoadHTMLFiles("../templates/login.html")
// 获取form表单提交数据
r.GET("/login", func(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
})
// 获取数据
r.POST("/login", func(c *gin.Context) {
// 方式二
username := c.DefaultPostForm("username", "body") // 取不到key,则值为默认值body
password := c.DefaultQuery("password", "123")
c.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
})
})
r.Run(":9999")
}
三、GetPostForm方式
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.LoadHTMLFiles("../templates/login.html")
// 获取form表单提交数据
r.GET("/login", func(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
})
// 获取数据
r.POST("/login", func(c *gin.Context) {
// 方式三
username, ok := c.GetPostForm("username")
if !ok {
username = "body"
}
password, ok := c.GetPostForm("password")
if !ok {
password = "sdfsdf"
}
c.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
})
})
r.Run(":9999")
}
在当下的阶段,必将由程序员来主导,甚至比以往更甚。