drpfu51608120170 2014-05-30 12:47
浏览 63
已采纳

在Go中验证结构的惯用方式?

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.

  • 写回答

8条回答 默认 最新

  • doudi5524 2014-05-30 13:19
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?