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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题