一、问题引出
如果通过前端向后端传递数据,你可能会这样进行接收:
1、前台
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/do_index" method="post">
用户名:<input type="text" name="username"> <br>
密 码:<input type="password" name="password"> <br>
<input type="submit">
</form>
</body>
</html>
显然,前台提交了一个form表单到后台。
2、后台
...
func DoIndex(ctx *gin.Context) {
username := ctx.PostForm("username")
password := ctx.PostForm("password")
fmt.Printf("username:%s,pasword:%s", username, password)
ctx.String(http.StatusOK, "submit success!")
}
...
可以看到后台通过ctx.PostForm方式逐一获取所有的参数值,那么有没有一种简单方式来解决这个问题,这就是我们所说的通过数据绑定的方式。
二、数据绑定引入
Gin提供了两种类型的绑定:
- MustBind
- ShouldBind
1、ShouldBind
它包含多种方法,如:ShouldBind,ShouldBindJSON,ShouldBindXML,ShouldBindQuery,ShouldBindYAML。这些方法属于ShouldBindWith的具体调用, 如果发生绑定错误,Gin 会返回错误并由开发者处理错误和请求。
ShouldBind可以绑定Form、QueryString、Json,uri
- 前台
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/do_bind_index" method="post">
用户名:<input type="text" name="username"> <br>
密 码:<input type="password" name="password"> <br>
<input type="submit">
</form>
</body>
</html>
- 后台
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type LoginInfo struct {
UserName string `form:"username" json:"username"`
PassWord string `form:"password" json:"password"`
}
func BindIndex(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "bind_index.html", nil)
}
func DoBindIndex(ctx *gin.Context) {
// 将form表单字段绑定到结构体上
var loginInfo LoginInfo
_ = ctx.ShouldBind(&loginInfo)
fmt.Printf("UserName:%s,PassWord:%s", loginInfo.UserName, loginInfo.PassWord)
ctx.String(http.StatusOK, "submit success!")
}
func main() {
router := gin.Default()
router.LoadHTMLGlob("template/*")
// 数据绑定
router.GET("/bind_index", BindIndex)
router.POST("/do_bind_index", DoBindIndex)
router.Run(":8080")
}
2、MustBind
可以绑定Form、QueryString、Json等,与ShouldBind的区别在于,ShouldBind没有绑定成功不报错,就是空值,MustBind会报错。
原创文章,作者:1402239773,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/245319.html