数据绑定的目的是前端提交过来的数据和后台数据进行映射
/*
@Author : 寒云
@Email : 1355081829@qq.com
@Time : 2019/10/15 11:51
*/
package main
import (
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
type User struct {
Name string `form:"user" binding:"required"`
Password string `form:"password" binding:"required"`
}
func main() {
r := gin.Default()
r.POST("/login", func(c *gin.Context) {
var user User
_ = c.ShouldBind(&user)
name := c.PostForm("name")
age := c.PostForm("age")
realAge, _ := strconv.Atoi(age)
c.JSON(http.StatusOK, gin.H{"user": user, "name": name, "age": realAge})
})
_ = r.Run(":8089")
}
在这个例子中,我们定义了个名字为User的机构体,
type User struct {
Name string `form:"user" binding:"required"`
Password string `form:"password" binding:"required"`
}
通过 ShouldBind将前台数据和我们的结构体进行了数据绑定
_ = c.ShouldBind(&user)
用postman模拟接口请求,我们成功的将前台请求的数据和我们定义的结构体绑定
image.png
网友评论