Lzs 2019-10-16
目前大都是使用 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") }