使用验证器检查值是否为布尔值



我是Go新手,所以这可能很容易,但我找不到。我有一个实体Page,它有以下两个属性:

type Page struct {
Title   string `form:"title" binding:"required"`
Active  bool
}

现在,如果您不发送标题,我们会得到一个(不是很漂亮,但可以接受*(:
Key: 'Page.Title' Error:Field validation for 'Title' failed on the 'required' tag

现在,如果我把这个发送到端点:

{
"title": "I'm a valid title",
"active": "I'm not a boolean at all!"
}

我们得到的是:
json: cannot unmarshal string into Go struct field Page.Active of type bool

国际海事组织提供的信息太多了。Go中验证用户输入的标准做法是什么?

我首先做了一个带有一些检查的page-validor.go,然后我发现了这个,但我不确定围棋中什么是好的练习
如何正确验证?我应该找到检查提供的内容,然后尝试将其移动到结构中并验证实际内容吗?

我正在使用GinGonic
*我找到了一种方法来打开错误并使其更好地

为类型Page编写自定义JSON Unmarshaller方法,在UnmarshalJSON(bytes []byte)方法中,您可以将JSON字节解组为map[string]interface{},然后使用JSON字段键验证所需的类型。

JSON Unmarshaller的一个示例如下所示。

type Page struct {
Title  string `form:"title" binding:"required"`
Active bool
}
func (p *Page) UnmarshalJSON(bytes []byte) error {
var data map[string]interface{}
err := json.Unmarshal(bytes, &data)
if err != nil {
return err
}
actv, _ := data["active"]
if reflect.TypeOf(actv).Kind() != reflect.Bool {
return errors.New("active field should be a boolean")
}
p.Active = actv.(bool)
return nil
}

请参阅Playground中的完整示例。

经过更多的研究,我实现了Go映射模式。

var page Page
src := make(map[string]interface{})
json.Unmarshal(jsonData, &src)
results, _ := schema.CompareMapToStruct(page, src, nil)
fmt.Println(results.MissingFields)
fmt.Println(results.MismatchedFields)

这对于结构的标准符号来说很简单:

type Page struct {
Title  string `json:"title" validator:"required"`
Active bool   `json:"metaRobotsFollow" validate:"required,bool"`
}

您应该使用Go 提供的验证器v10

验证器文档go

对于您的用例,您可以使用布尔验证器
https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-布尔

type Page struct {
Title  string `json:"title" binding:"required"`
Active bool   `json:"active" binding:"required,boolean"`
}

以下是带有一个阳性和阴性的测试用例样本

func TestPage(t *testing.T) {
tests := []struct {
testName string
input    string
wantErr  bool
}{
{
testName: "positive test",
input: `{
"title": "first book title",
"active": false
}`,
wantErr: false,
}, {
testName: "wrong boolean",
input: `{
"title": "second book title",
"active": falsee
}`,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
var p Page
b := []byte(tt.input)
err := json.Unmarshal(b, &p)
assert.Nil(t, err, "got error %v", err)
})
}

最新更新