gin表单验证struct tag

本文是对 validate tag not working in ShouldBindWith 的回答。

有人提了这么一个问题:

golang 复制代码
package main

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// MyStruct ..
type MyStruct struct {
	Order string `form:"order,default=DESC" validate:"omitempty,oneof=ASC DESC"`
}

func startPage(c *gin.Context) {
	var person MyStruct
	if c.ShouldBindWith(&person, binding.Query) == nil {
		log.Println("====== Only Bind By Query String ======")
		log.Println(person.Order)
		c.String(http.StatusOK, "Success")
		return
		// log.Println(person.Address)
	}
	c.String(http.StatusBadRequest, "Failed")
	return
}

func main() {

	route := gin.Default()
	route.Any("/testing", startPage)
	route.Run(":8085")
}

然后表单验证的时候,明明 Order 传递了一个不符合 oneof=ASC DESC 的值,但却验证通过了。

原因

虽然 gin 使用了 go-playground/validator 来作为表单验证的组件,但是在 gin 里面却修改了 struct 验证的 tagname,我们可以看看 default_validator.go#L95

golang 复制代码
func (v *defaultValidator) lazyinit() {
	v.once.Do(func() {
		v.validate = validator.New()
		v.validate.SetTagName("binding")
	})
}

然后,我们就不能通过给 struct 加上 vaidate 的 tag 来写上我们的验证规则,取而代之的是,需要将我们的验证规则写在 binding 这个 tag 里面:

validate:"omitempty,oneof=ASC DESC" 替换成 binding:"omitempty,oneof=ASC DESC",我们即可实现在 gin 中使用 validator 验证我们的 struct。

golang 复制代码
type MyStruct struct {
	Order string `form:"order,default=DESC" binding:"omitempty,oneof=ASC DESC"`
}

参考官方文档:
模型绑定和验证

相关推荐
007php0074 小时前
PHP与Java项目在服务器上的对接准备与过程
java·服务器·开发语言·分布式·面试·职场和发展·php
Evand J5 小时前
【MATLAB程序,一维非线性EKF与RTS】MATLAB,用于一维的位移与速度滤波和RTS平滑/高精度定位,带滤波前后的误差对比
开发语言·matlab·卡尔曼滤波·rts平滑·正向滤波
火云洞红孩儿10 小时前
告别界面孤岛:PyMe如何用一站式流程重塑Python GUI开发?
开发语言·python
叫我辉哥e110 小时前
新手进阶Python:办公看板集成ERP跨系统同步+自动备份+AI异常复盘
开发语言·人工智能·python
晚风吹长发10 小时前
初步了解Linux中的命名管道及简单应用和简单日志
linux·运维·服务器·开发语言·数据结构·c++·算法
C++ 老炮儿的技术栈11 小时前
不调用C++/C的字符串库函数,编写函数strcpy
c语言·开发语言·c++·windows·git·postman·visual studio
布局呆星11 小时前
闭包与装饰器
开发语言·python
fyzy11 小时前
C++写后端实现,实现前后端分离
开发语言·c++
huohuopro11 小时前
Mybatis的七种传参方式
java·开发语言·mybatis
Lee_SmallNorth11 小时前
变态需求之【角色不同访问数据库的用户不同】
java·开发语言·数据库