在Go中验证结构的习惯性方法? [英] Idiomatic way to validate structs in Go?

查看:131
本文介绍了在Go中验证结构的习惯性方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证一个struct值是否正确,这意味着我需要单独检查每个字段,这对于少量小型结构很容易,但是我想知道是否有更好的方法来实现它。

I need to validate that a struct value is correct and this means I need to check every field individually, which is easy for a small number of small structs but I was wondering if there's a better way to do it. Here's how I'm doing it right now.

type Event struct {
    Id     int
    UserId int
    Start  time.Time
    End    time.Time
    Title  string
    Notes  string
}

func (e Event) IsValid() error {
    if e.Id <= 0 {
        return errors.New("Id must be greater than 0")
    }
    if e.UserId <= 0 {
        return errors.New("UserId must be greater than 0")
    }
    if e.End <= e.Start {
        return errors.New("End must be after Start")
    }
    if e.Start < time.Now() {
        return errors.New("Cannot create events in the past")
    }
    if e.Title == "" {
        return errors.New("Title cannot be empty")
    }
    return nil
}

这是验证结构中字段值的惯用方法吗?它看起来很麻烦。

Is this the idiomatic way to validate the values of fields in a struct? It looks cumbersome.

推荐答案

我没有看到任何其他方式快速执行此操作。但是我找到了一个可以帮助你的软件包: https://github.com/go-validator/validator

I don't see any other way to do this quickly. But I found a go package which can help you with this: https://github.com/go-validator/validator

自述文件给出了这个例子:

The README file gives this example:

type NewUserRequest struct {
    Username string `validator:"min=3,max=40,regexp=^[a-zA-Z]$"`
    Name string     `validator:"nonzero"`
    Age int         `validator:"min=21"`
    Password string `validator:"min=8"`
}

nur := NewUserRequest{Username: "something", Age: 20}
if valid, errs := validator.Validate(nur); !valid {
    // values not valid, deal with errors here
}

这篇关于在Go中验证结构的习惯性方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆