当前位置:网站首页>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
边栏推荐
- 5G China unicom 一般性异常处理
- 正则引擎的几种分类
- 5G China unicom AP:B SMS ASCII Transcoding Requirements
- novel research
- The new features of ABP 6.0.0 - rc. 1
- 一维数组&指针
- telnet+ftp to control and upgrade the device
- Flutter introduction advanced trip (5) Image Widget
- 史上最猛“员工”,疯狂吐槽亿万富翁老板小扎:那么有钱,还总穿着同样的衣服!...
- Flutter Getting Started and Advanced Tour (4) Text Input Widget TextField
猜你喜欢
随机推荐
农村区县域农业电商如何做?数字化转型如何进行?
Standing wave ratio calculation method
陈强教授《机器学习及R应用》课程 第十五章作业
Flutter Getting Started and Advanced Tour (3) Text Widgets
[HCIP Continuous Update] Principle and Configuration of IS-IS Protocol
2.微服务'黑话'集锦及Eureka注册中心相关概念
在“Extend the Omniverse”比赛中构建用于 3D 世界的工具
SQL Server查询优化 (转载非原创)
时间序列分析课程实验报告
十六进制字符→十进制数字
【FPGA教程案例48】图像案例8——基于FPGA的RGB图像转化为HSV图像的实现,通过MATLAB进行辅助验证
How to save Simulink simulation model as image or PDF
leetcode 20. Valid Parentheses 有效的括号(中等)
电脑重装系统还原0x80070005错误如何解决
NFS 特别注意权限的问题
在已打开图片上加水印(文字)
Simple encapsulation of glide tool class
LeetCode 37.解数独
FPGA-在ISE中错误总结(更新中)
30行代码实现微信朋友圈自动点赞