golang之数据校验的实现代码示例
目前大都是使用 validator
安装
go get gopkg.in/go-playground/validator.v9
原理
当然只能通过反射来实现了,之前写过一篇反射的文章 golang之反射和断言 ,里面有写到怎么通过反射获取struct tag。
读取struct tag之后就是对里面的标识符进行识别,然后进行验证了。具体可以去看源码。
demo
简单使用:
package main import ( "fmt" "gopkg.in/go-playground/validator.v9" ) // User contains user information type UserInfo struct { FirstName string `validate:"required"` LastName string `validate:"required"` Age uint8 `validate:"gte=0,lte=100"` Email string `validate:"required,email"` } func main() { validate := validator.New() user := &UserInfo{ FirstName: "Badger", LastName: "Smith", Age: 105, Email: "", } err := validate.Struct(user) if err != nil { for _, err := range err.(validator.ValidationErrors) { fmt.Println(err) } return } fmt.Println("success") }
输出:
Key: 'UserInfo.Age' Error:Field validation for 'Age' failed on the 'lte' tag
Key: 'UserInfo.Email' Error:Field validation for 'Email' failed on the 'required' tag
其它类型可以参照文档 https://godoc.org/gopkg.in/go-playground/validator.v9
几个例子:
1.IP type UserInfo struct { Ip string `validate:"ip"` } 2.数字 type UserInfo struct { Number float32 `validate:"numeric"` } 3.最大值 type UserInfo struct { Number float32 `validate:"max=10"` } 4.最小值 type UserInfo struct { Number float32 `validate:"min=10"` }
自定义验证函数
package main import ( "fmt" "gopkg.in/go-playground/validator.v9" "unicode/utf8" ) // User contains user information type UserInfo struct { Name string `validate:"checkName"` Number float32 `validate:"numeric"` } // 自定义验证函数 func checkName(fl validator.FieldLevel) bool { count := utf8.RuneCountInString(fl.Field().String()) fmt.Printf("length: %v \n", count) if count > 5 { return false } return true } func main() { validate := validator.New() //注册自定义函数,与struct tag关联起来 err := validate.RegisterValidation("checkName", checkName) user := &UserInfo{ Name: "我是中国人,我爱自己的祖国", Number: 23, } err = validate.Struct(user) if err != nil { for _, err := range err.(validator.ValidationErrors) { fmt.Println(err) } return } fmt.Println("success") }
相关推荐
hellofeiya 2020-11-12
lanmantech 2020-08-15
abdstime 2020-02-22
herohope 2020-01-05
蜗牛慢爬的李成广 2019-12-22
HSdiana 2019-12-15
feinifi 2019-10-08
MrHaoNan 2019-10-29
ljsfighting 2019-10-29
morexyoung 2019-10-29
laofangzi 2019-10-26
zhujiangtaotaise 2019-10-24
benny0 2019-06-11
jsjcaowei 2019-05-23
Ctommy 2018-03-22
HiUnicorn 2019-07-01
tangxiong0 2019-06-30