介绍
本文介绍 gin中multipart/urlencoded绑定, 用户 post 指定数据后,如符合要求则给出对应的输出。
案例
代码
package main
import (
"github.com/gin-gonic/gin"
)
type LoginForm struct {
User string `form:"user" binding:"required"`
Password string `form:"password" binding:"required"`
}
func main() {
router := gin.Default()
router.POST("/login", func(c *gin.Context) {
// 你可以使用显式绑定声明绑定 multipart form:
// c.ShouldBindWith(&form, binding.Form)
// 或者简单地使用 ShouldBind 方法自动绑定:
var form LoginForm
// 在这种情况下,将自动选择合适的绑定
if c.ShouldBind(&form) == nil {
if form.User == "user" && form.Password == "password" {
c.JSON(200, gin.H{"status": "you are logged in"})
} else {
c.JSON(401, gin.H{"status": "unauthorized"})
}
}
})
router.Run(":8080")
}
其中 form:“user” 表示前端提交form表单时User对应的key的名称为:user
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<form action="http://localhost:8080/login" method="post" enctype="application/x-www-form-urlencoded">
用户名<input type="text" name="user"><br>
密码<input type="password" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>
测试
$ curl -v --form user=user --form password=password http://localhost:8080/login
* Trying 127.0.0.1:8080...
...
<
* Connection #0 to host localhost left intact
{"status":"you are logged in"}
$ curl localhost:8080/login --form user=user --form password=password1
{"status":"unauthorized"}
web 测试: