当前位置:网站首页>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
边栏推荐
- jenkins api创建自定义pipeline
- Redis源码剖析之字典(dict)
- 在“Extend the Omniverse”比赛中构建用于 3D 世界的工具
- FFmpeg多媒体文件处理(ffmpeg操作目录及list的实现)
- WebView injects Js code to realize large image adaptive screen click image preview details
- 腾讯发布第二代四足机器人Max,梅花桩上完成跳跃、空翻
- 农村区县域农业电商如何做?数字化转型如何进行?
- FPGA - Summary of bugs in ISE (in update)
- RTSP协议讲解
- 驻波比计算方法
猜你喜欢

ansible-cmdb friendly display ansible collects host information

Jenkins API groovy calling practice: Jenkins Core Api & Job DSL to create a project

Compensation transaction and idempotency guarantee based on CAP components

快来扔鸡蛋。

RTSP协议讲解

Anta and Huawei Sports Health jointly verify the champion running shoes and lead Chinese sports with innovation

How to solve the 0x80070005 error when the computer is reinstalled and the system is restored

kustomize入门示例及基本语法使用说明

第六届“强网杯”全国网络安全挑战赛

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)
随机推荐
Ten minutes to teach you how to use VitePress to build and deploy a personal blog site
昇腾AI开发者创享日南京站!一起CANN机器狗+AI机械臂实现硬核智慧救援!燃爆现场~
Rust from entry to proficient 04 - data types
驻波比计算方法
Flutter introduction advanced trip (5) Image Widget
剑指offer,剪绳子2
[MRCTF2020]套娃-1
陈强教授《机器学习及R应用》课程 第十五章作业
Flutter Getting Started and Advanced Tour (8) Button Widget
telnet+ftp to control and upgrade the device
ftplib+ tqdm upload and download progress bar
glibc 内存管理模型 释放 C库内存缓存
正则引擎的几种分类
[FPGA Tutorial Case 48] Image Case 8 - Realization of Converting RGB Image to HSV Image Based on FPGA, Assisted Verification by MATLAB
Clock frequency and baud rate count for serial communication in FPGA
Explanation of RTSP protocol
剑指 Offer 56 - II. 数组中数字出现的次数 II(位运算)
FFmpeg多媒体文件处理(ffmpeg处理流数据的基本概念)
jenkins api创建自定义pipeline
农村区县域农业电商如何做?数字化转型如何进行?