当前位置:网站首页>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
边栏推荐
- 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面(循环不变量)
- Sandbox中的进程/线程相关-2
- 记录本项目中用到的系统调用与C库函数-2
- 用plot_hist_numeric()实现画直方图
- Clock frequency and baud rate count for serial communication in FPGA
- About the handling of variable parameters in the Retrofit network request URL
- 中断系统结构及中断控制详解
- 5G China unicom AP:B SMS ASCII Transcoding Requirements
- jenkins api create custom pipeline
- 电脑重装系统后桌面图标如何调小尺寸
猜你喜欢
Data Mining-05
WSA toolkit installed app store tip doesn't work how to solve?
Intra-group reverse order adjustment of K nodes
FFmpeg多媒体文件处理(ffmpeg操作目录及list的实现)
Redis源码剖析之跳表(skiplist)
面试题精选:神奇的斐波那契数列
造自己的芯,让谷歌买单!谷歌再度开源 180nm 工艺的芯片
Do you know the difference between comments, keywords, and identifiers?
Explanation of RTSP protocol
kustomize入门示例及基本语法使用说明
随机推荐
LnReader编译
乐东消防救援大队应邀为干部开展消防安全培训
造自己的芯,让谷歌买单!谷歌再度开源 180nm 工艺的芯片
陈强教授《机器学习及R应用》课程 第十四章作业
工作任务统计
单面线路板与精密多层PCB线路板区别有哪些?
NFS 特别注意权限的问题
leetcode 20. Valid Parentheses 有效的括号(中等)
【FPGA教程案例48】图像案例8——基于FPGA的RGB图像转化为HSV图像的实现,通过MATLAB进行辅助验证
The FPGA - work summary recently
ARM板卡增加路由功能
七夕力扣刷不停,343. 整数拆分(剑指 Offer 14- I. 剪绳子、剑指 Offer 14- II. 剪绳子 II)
Redis源码剖析之数据过期(expire)
某高校的R语言数据分析期末作业
RTSP协议的实现
LeetCode 37.解数独
Use RecyclerView to implement three-level collapsed list
Flutter Getting Started and Advanced Tour (2) Hello Flutter
R 语言 2010.1至2021.12艾滋病每月发病人数 时间序列分析
5G China unicom 一般性异常处理