我是高朗的新手。高朗版本:1.17.8驗證器:“ github.com/go-playground/validator/v10 ”我想在加載到嵌套結(jié)構(gòu)數(shù)據(jù)結(jié)構(gòu)后驗證傳入的 JSON 有效負載。這是我傳入的 JSON 負載, { "name": "Yomiko", "address": { "city": "Tokyo", "street": "Shibaura St" }, "children":[ { "lastName": "Takayashi" } ], "isEmployed": false }這是我的 user.go 文件,package maintype User struct { Name string Address *Address `validate:"required"` Children []*Child IsEmployed *bool `validate:"required"`}type Address struct { City string `validate:"required"` Street string `validate:"required"`}type Child struct { Title string `validate:"required"` FirstName string LastName string `validate:"required"`}這是我的測試功能,func TestUserPayload(t *testing.T) { actualUserPayload := NewUserPayloadFromFile("userpayload.json") validate := validator.New() err := validate.Struct(actualUserPayload) if err != nil { t.Error("Validation Error: ", err) }}這個測試通過。但是,我預(yù)計它會失敗,因為Child.Title被標記為required。我預(yù)計會出現(xiàn)以下錯誤,Validation Error: Key: 'Child.Title' Error:Field validation for 'Title' failed on the 'required' tag但是,當(dāng)我循環(huán)遍歷子切片并按如下方式驗證每個子結(jié)構(gòu)時,測試按預(yù)期失敗,func TestUserPayload(t *testing.T) { actualUserPayload := NewUserPayloadFromFile("userpayload.json") validate := validator.New() err := validate.Struct(actualUserPayload) if err != nil { t.Error("Validation Error: ", err) } children := actualUserPayload.Children for _, child := range children { err := validate.Struct(child) if err != nil { t.Error("Validation Error: ", err) } }}有沒有一種直接的方法來驗證一片結(jié)構(gòu)中的項目?
Golang:驗證切片項中的結(jié)構(gòu)字段
阿波羅的戰(zhàn)車
2022-12-19 21:31:17