当前位置:网站首页>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

原网站

版权声明
本文为[One Leaf Knows Autumn @qqy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208091244282196.html