我需要验证结构值是否正确,这意味着我需要单独检查每个字段,这对于少数小型结构来说很容易,但我想知道是否有更好的方法来做到这一点。这就是我现在的做法。
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
}
这是验证结构中字段值的惯用方式吗?看起来很麻烦。
最佳答案
我看不出有任何其他方法可以快速做到这一点。但是我找到了一个可以帮助你解决这个问题的包:https://github.com/go-validator/validator
README 文件给出了这个例子:
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
}
关于validation - 验证结构的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23955036/