Galidator - 一个实现结构或地图字段验证的包验证器

85 阅读1分钟

伽利略验证器

Galidator是一个包验证器,实现了结构或地图字段的验证。

安装方法

只需使用go get 进行安装:

go get github.com/golodash/galidator

然后在你的代码中导入该包即可:

import (
	"github.com/golodash/galidator"
)

使用实例

例子-1

import (
    "fmt"
	"github.com/golodash/galidator"
)

func main() {
	g := galidator.New()
	schema := g.Generate(galidator.Items{
		"number": g.Item().Int(),
		"id":     g.Item().Float(),
	}, nil)

	output := map[string]string{
		"number": "15", // Valid int data
		"id":     "125s", // Invalid float data
	}
	fmt.Println(schema.Validate(output))
}

输出:

map[id:[id is not float]]

例子-2

import (
	"fmt"

	"github.com/golodash/galidator"
)

type testStruct struct {
	Number int
	ID     string
}

func main() {
	g := galidator.New()
	schema := g.Generate(galidator.Items{
		"Number": g.Item().Int(),
		"ID":     g.Item().Float(),
	}, nil)

	output := testStruct{
		Number: 15,        // Valid int data
		ID:     "125.23d", // Invalid float data
	}
	fmt.Println(schema.Validate(output))
}

输出:

map[ID:[ID is not float]]