簡體   English   中英

使用驗證器檢查值是否為 boolean

[英]Using validator to check if value is boolean

我是 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

哪個,IMO,提供了太多信息。 Go 中驗證用戶輸入的標准做法是什么?

我首先制作了一個page-validor.go並進行了一些檢查,然后我發現了這個,但我不確定 Go 中有什么好的做法。
如何正確驗證這一點? 我是否應該檢查所提供的內容,然后嘗試將其移動到結構中並驗證實際內容?

我正在使用GinGonic
* 我找到了一種方法來解開錯誤並讓它變得更好

Write custom JSON Unmarshaller method for the type Page and inside UnmarshalJSON(bytes []byte) method, you can unmarshal the JSON bytes to map[string]interface{} and then validate the types you need with the JSON field keys.

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-map-schema

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" validator:"required,bool"`
}

您應該使用 Go 提供的驗證器 v10

驗證器文檔 go

對於您的用例,您可以使用boolean驗證器
https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Boolean

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)
    })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM