gin中模型的绑定和验证
要将请求体绑定到结构体中,使用模型绑定。 Gin目前支持JSON、XML、YAML和标准表单值的绑定(foo=bar&boo=baz)。
Gin使用 go-playground/validator/v10 进行验证。 查看标签用法的全部文档.
使用时,需要在要绑定的所有字段上,设置相应的tag。 例如,使用 JSON 绑定时,设置字段标签为 json:"fieldname"。
Gin提供了两类绑定方法:
- Type - Must bind
- Methods -
Bind,BindJSON,BindXML,BindQuery,BindYAML - Behavior - 这些方法属于
MustBindWith的具体调用。 如果发生绑定错误,则请求终止,并触发c.AbortWithError(400, err).SetType(ErrorTypeBind)。响应状态码被设置为 400 并且Content-Type被设置为text/plain; charset=utf-8。 如果您在此之后尝试设置响应状态码,Gin会输出日志[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422。 如果您希望更好地控制绑定,考虑使用ShouldBind等效方法。
- Methods -
- Type - Should bind
- Methods -
ShouldBind,ShouldBindJSON,ShouldBindXML,ShouldBindQuery,ShouldBindYAML - Behavior - 这些方法属于
ShouldBindWith的具体调用。 如果发生绑定错误,Gin 会返回错误并由开发者处理错误和请求。
- Methods -
使用 Bind 方法时,Gin 会尝试根据 Content-Type 推断如何绑定。 如果你明确知道要绑定什么,可以使用 MustBindWith 或 ShouldBindWith。
你也可以指定必须绑定的字段。 如果一个字段的 tag 加上了 binding:"required",但绑定时是空值, Gin 会报错。
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Login struct {
// binding: "-" // - 表示可以不传递该参数
User string `json:"user" form:"user" xml:"user" binding:"required"`
Password string `json:"password" form:"password" xml:"password" binding:"required"`
}
func main() {
// 模型的绑定和验证
// 1. JSON的绑定和验证
//r := gin.Default()
//r.POST("/", func(context *gin.Context) {
// var login Login
// if err := context.ShouldBindJSON(&login); err != nil {
// context.String(http.StatusBadRequest, err.Error())
// return
// }
// if login.User != "li" || login.Password != "123456" {
// context.JSON(http.StatusUnauthorized, gin.H{"err": "unauthorized"})
// return
// }
// context.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
//})
//r.Run()
// 2. 表单的绑定和验证
//r := gin.Default()
//r.POST("/", func(context *gin.Context) {
// var login Login
// // 根据Content-Type header 推断用哪个绑定器
// if err := context.ShouldBind(&login); err != nil {
// context.String(http.StatusBadRequest, err.Error())
// return
// }
// if login.User != "li" || login.Password != "123456" {
// context.JSON(http.StatusUnauthorized, gin.H{"err": "unauthorized"})
// return
// }
// context.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
//})
//r.Run()
// 3. xml的绑定和验证
/* xml格式:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<user>li</user>
<password>123456</password>
</root>
*/
r := gin.Default()
r.POST("/", func(context *gin.Context) {
var login Login
if err := context.ShouldBindXML(&login); err != nil {
context.String(http.StatusBadRequest, err.Error())
return
}
if login.User != "li" || login.Password != "123456" {
context.JSON(http.StatusUnauthorized, gin.H{"err": "unauthorized"})
return
}
context.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
})
r.Run()
}
validator 参考链接:
1. github: https://github.com/go-playground/validator
2. document: https://pkg.go.dev/github.com/go-playground/validator/v10#section-documentation

浙公网安备 33010602011771号