大家好,我是欧盆索思(opensource),每天为你带来优秀的开源项目!
表单验证,Go 圈最知名的应该是 https://github.com/go-playground/validator ,很强大,Gin 框架用的就是它。今天要介绍的,是字节跳动开源的一个类似的库,即 go-tagexpr。
项目地址:https://github.com/bytedance/go-tagexpr,Star 数 766。
官方介绍,这是一个有趣的 go struct 标记表达式语法,用于字段验证等。支持数据绑定和验证。
主要特性有:
支持多种常用运算符
支持访问数组,切片,字典成员
支持访问当前结构中的任何字段
支持访问嵌套字段,非导出字段等。
支持寄存器功能表达式
内置 len,sprintf,regexp 函数
支持单模和多模定义表达式
参数检查子包
使用偏移量指针直接获取值,获得更好的性能
看一个例子代码:
type T struct {
A int `tagexpr:"$<0||$>=100"`
B string `tagexpr:"len($)>1 && regexp('^\\w*$')"`
C bool `tagexpr:"expr1:(f.g)$>0 && $; expr2:'C must be true when T.f.g>0'"`
d []string `tagexpr:"@:len($)>0 && $[0]=='D'; msg:sprintf('invalid d: %v',$)"`
e map[string]int `tagexpr:"len($)==$['len']"`
e2 map[string]*int `tagexpr:"len($)==$['len']"`
f struct {
g int `tagexpr:"$"`
}
}