当前位置:网站首页>GIN Bind mode to get parameters and form validation
GIN Bind mode to get parameters and form validation
2022-08-09 13:48:00 【One Leaf Knows Autumn @qqy】
前言
感谢开源项目gin-vue-admin,以及1010工作室的教程,项目文档
我只是在跟着学习,然后记录下笔记而已,可能会有新的代码加入,但是本质还是跟着学习的一个过程.
The so-called binding is to create a structure first,Then the received parameters are directly mapped in the form of binding
bindmode and how to use it
There are two ways to use binding mode,即must bind和should bind.
must bind
- Methods:
Bind, BindJSON, BindXML, BindQuery, BindYAML - Behavior This time the method is used at the bottomMustBindWith,如果存在绑定错误,请求将被以下指令中止
c.AbortWithError(400, err).SetType(ErrorTypeBind),响应状态代码会被设置为400,请求头Content-Type被设置为text/plain; charset=utf-8.
注意,如果你试图在此之后设置响应代码,将会发出一个警告 [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422,
If you want more control over the behavior,请使用ShouldBind相关的方法
should bind
- Mwthods:
ShouldBind, ShouldBindJSON, ShouldBindXML, ShouldBindQuery, ShouldBindYAML - Behavior:
这些方法底层使用ShouldBindWith如果存在绑定错误,则返回错误,Developers can request and bug correctly.
When we use the binding method,Gin会根据Content-TypeInfer which binder to use,If you are sure what you are binding,你可以使用MustBindWith或者BindingWith
ShouldBindJSON
在goland中写下如下代码:
package main
import (
"github.com/gin-gonic/gin"
)
type PostParams struct {
Name string `json:"name"`
Age int `json:"age"`
Sex bool `json:"sex"`
}
func main() {
r := gin.Default() //启动gin路由,携带基础中间件启动 logger and recovery (crash-free) 中间件
r.POST("testBind", func(c *gin.Context) {
var p PostParams
err := c.ShouldBindJSON(&p)
if err != nil{
c.JSON(200, gin.H{
"msg":"报错了",
"data":gin.H{
},
})
}else{
c.JSON(200, gin.H{
"msg":"成功了",
"data":p,
})
}
})
r.Run(":1010") // listen and serve on 0.0.0.0:8080
}
The following things are done here:
创建PostParams结构体
Make the following definitions in it:
type PostParams struct {
Name string `json:"name"`
Age int `json:"age"`
Sex bool `json:"sex"`
}
It can be seen that the three elements in this are all allowed to be bound to their corresponding onesjson上了.
使用ShouldBindJSON
首先实例化PostParams
var p PostParams
Call the interface to implement map resolution,并返回错误码
err := c.ShouldBindJSON(&p)
Respond according to the returned result
if err != nil{
c.JSON(200, gin.H{
"msg":"报错了",
"data":gin.H{
},
})
}else{
c.JSON(200, gin.H{
"msg":"成功了",
"data":p,
})
}
postman组织请求


It can be seen that the correct return response has been obtained
ShouldBindUri
修改PostParams结构体
Make an addition in it as followsuri的字段:
type PostParams struct {
Name string `json:"name" uri:"name"`
Age int `json:"age" uri:"age"`
Sex bool `json:"sex" uri:"sex"`
}
It can be seen that the three elements in this are all allowed to be bound to their corresponding onesuri上了.
更改访问网址
Because it was shown at the beginningjson的绑定,即从bodyTake parameters inside,但是现在使用uribig way,To put parameters inside the URL.
So will the original URL parttestBind替换为
testBind/:name/:sge/:sex
并将ShouldBindJSON更换为ShouldBindUri
组织postman访问


ShouldBindQuery
修改PostParams结构体
Make an addition in it as followsQuery对应form的字段:
type PostParams struct {
Name string `json:"name" uri:"name" form:"name"`
Age int `json:"age" uri:"age" form:"age"`
Sex bool `json:"sex" uri:"sex" form:"sex"`
}
更改访问网址
Restore the original URL portion to testBind替换
并将ShouldBindUri更换为ShouldBindQuery
组织postman访问


ShouldBind
The above binding can see that only one type can be received at a time,So when there may be multiple types at the same time,Apparently it can't be dealt with like this anymore,So it can be used in this caseShouldBind
如果是Post, 首先判断 content-type 的类型 JSON or XML, 然后使用对应的绑定器获取数据.
See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48
如下面postman截图中所示
表单验证binding
修改PostParams结构体
在里面添加如下binding的字段:
type PostParams struct {
Name string `json:"name" binding:"required"`
Age int `json:"age" binding:"required"`
Sex bool `json:"sex" binding:"required"`
}
在这里加入required修饰符,At this time, if the parameter with the modifier is added, it will be empty,那么会直接报错
Replace the binder with ShouldBindJSON
组织postman

可以发现,When there is an empty request, an error is reported directly.
Add printing to the code,See the specific error message below
Apparently it is an error caused by not filling in the required fields every day
自定义验证器
首先在PostParams结构体的bindingAdd a custom labelmustBig,Then define a validator,An example of this tag name:
func mustBig(fl validator.FieldLevel)bool{
if(fl.Field().Interface().(int) <= 18){
return false
}
return true
}
passed inside the functionvalidator.FieldLevel对象,Internally, it is asserted in the form of reflection,并作判断,返回truw 或者 falseReturns whether the current validation rule passed
在mainMount this validator inside the function
if v, ok := binding.Validator.Engine().(*validator.Validate); ok{
v.RegisterValidation("mustBig", mustBig)
}
give the entire code:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
type PostParams struct {
Name string `json:"name"`
Age int `json:"age" binding:"required,mustBig"`
Sex bool `json:"sex"`
}
func mustBig(fl validator.FieldLevel)bool{
if(fl.Field().Interface().(int) <= 18){
return false
}
return true
}
func main() {
r := gin.Default() //启动gin路由,携带基础中间件启动 logger and recovery (crash-free) 中间件
r.POST("testBind", func(c *gin.Context) {
if v, ok := binding.Validator.Engine().(*validator.Validate); ok{
v.RegisterValidation("mustBig", mustBig)
}
var p PostParams
err := c.ShouldBindJSON(&p)
if err != nil{
fmt.Println(err)
c.JSON(200, gin.H{
"msg":"报错了",
"data":gin.H{
},
})
}else{
c.JSON(200, gin.H{
"msg":"成功了",
"data":p,
})
}
})
r.Run(":1010") // listen and serve on 0.0.0.0:8080
}
postman组织请求1

requested at this timeage是28greater than in the validator18,所以成功
postman组织请求2

requested at this timeage是8less than in the validator18,所以失败
所以使用bindingNot only can form validation,Validators can also be customized,This gives the code a lot of wiggle room
边栏推荐
猜你喜欢
随机推荐
Standing wave ratio calculation method
JVM之配置介绍(一)
FFmpeg多媒体文件处理(FFMPEG日志系统)
Uni - app - uview Swiper shuffling figure component, click on the links to jump (click to get the item after the row data, remove data operation)
Flutter Getting Started and Advanced Tour (2) Hello Flutter
阿里大淘系模型治理阶段性分享
批量读取word docx文件指定表格内容,保存在excel文件中
R语言kaggle 游戏数据探索与可视化
流量焦虑背后是企业对客户关系管理的不足
Sandbox中的进程/线程相关-2
RTSP协议的实现
About the handling of variable parameters in the Retrofit network request URL
ARM板卡增加路由功能
生成上传密钥和密钥库
SQL Server查询优化 (转载非原创)
RTSP协议讲解
WPF 实现带蒙版的 MessageBox 消息提示框
glibc 内存管理模型 释放 C库内存缓存
【FPGA教程案例48】图像案例8——基于FPGA的RGB图像转化为HSV图像的实现,通过MATLAB进行辅助验证
正则引擎的几种分类









