为了能够更方便的获取请求相关参数,提高开发效率,我们可以基于请求的Content-Type识别请求数据类型并利用反射机制自动提取请求中QueryString、form表单、JSON、XML等参数到结构体中。 下面的示例代码演示了.ShouldBind()强大的功能,它能够基于请求自动提取JSON、form表单和QueryString类型的数据,并把值绑定到指定的结构体对象。

前端

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
#index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ShouldBind</title>
</head>
<body>
<form action="/form" method="post">
    用户名:
    <input type="text" name="username">
    密码:
    <input type="password" name="password">
    <input type="submit" value="提交">
</form>
</body>
</html>

后端

#main.go
package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type UserInfo struct {
	Username string `form:"username" json:"user"`
	Password string `form:"password" json:"pass"`
}

func main() {
	r := gin.Default()
	r.LoadHTMLFiles("./index.html")
	r.GET("/user", func(c *gin.Context) {
		//username := c.Query("username")
		//password := c.Query("password")
		//u := UserInfo{
		//	username: username,
		//	password: password,
		//}

		var u UserInfo  //声明一个UserInfo类型的变量u
		err := c.ShouldBind(&u)  //?
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		} else {
			fmt.Printf("%#v\n",u)
			c.JSON(http.StatusOK, gin.H{
				"status":"ok",
			})
		}
	})

	r.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK,"index.html",nil)
	})

	r.POST("/json", func(c *gin.Context) {
		var u UserInfo  //声明一个UserInfo类型的变量u
		err := c.ShouldBind(&u)  //?
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		} else {
			fmt.Printf("%#v\n",u)
			c.JSON(http.StatusOK, gin.H{
				"status":"ok",
			})
		}
	})
	//c.JSON(http.StatusOK,gin.H{
	//	"message": "ok",
	//})
	r.Run(":9090")
}

验证

json:对应的是user、pass
gin系列-参数绑定 go 第1张
gin系列-参数绑定 go 第2张
gin系列-参数绑定 go 第3张
gin系列-参数绑定 go 第4张
总结

ShouldBind会按照下面的顺序解析请求中的数据完成绑定:
如果是 GET 请求,只使用 Form 绑定引擎(query)。
如果是 POST 请求,首先检查 content-type 是否为 JSON 或 XML,然后再使用 Form(form-data)。

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄