Golang验证程序无效的内存地址或nil指针取消引用

时间:2018-07-20 13:41:13

标签: validation go

包装

https://github.com/go-playground/validator

打包版本,例如v8,v9:

V9

问题,疑问或增强功能:

问题:按照教程进行操作,但是出现invalid memory address or nil pointer dereference错误

代码示例,用于展示或复制:

import  "gopkg.in/go-playground/validator.v9"
var validate *validator.Validate

func V1Register(w http.ResponseWriter, r *http.Request) {
    decoder := json.NewDecoder(r.Body)
    var params RegisterReq
    if err := decoder.Decode(&params); err != nil {
        log.Logger.Error("%s", err)
    }

    user := &models.User{
        Id:        10,
        Email:     params.Email,
        Username:  "asddas",
        ProfileId: 22,
        Password:  "rotroot",
        UserType:  10,
    }
    if err := models.CreateUser(user); err != nil {
        log.Logger.Notice("%s", err)
    }

    log.Logger.Info("%s", params.Email)
}

func CreateUser(user *User) (err error) {
    log.Logger.Info("%s", user)

    err = validate.Struct(user)
    if err != nil {
        return err
    }
    err = database.DBCon.Insert(user)
    if err != nil {
        return err
    }
    return nil
}

谢谢!

1 个答案:

答案 0 :(得分:0)

我忘记初始化验证器Field 3