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

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应