目前大都是使用 validator
安装
1
|
go get gopkg.in/go-playground/validator.v9
|
原理
当然只能通过反射来实现了,之前写过一篇反射的文章 golang之反射和断言 ,里面有写到怎么通过反射获取struct tag。
读取struct tag之后就是对里面的标识符进行识别,然后进行验证了。具体可以去看源码。
demo
简单使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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"`
}
|
自定义验证函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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")
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.tuicool.com/articles/ZZFNNrF