drpzr64329 2018-07-20 13:41
浏览 70
已采纳

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

Package

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

Package version eg. v8, v9:

V9

Issue, Question or Enhancement:

Question: Followed the tutorial, however, i get invalid memory address or nil pointer dereference error

Code sample, to showcase or reproduce:

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
}

Thanks!

  • 写回答

1条回答 默认 最新

  • dpz3471 2018-07-20 13:47
    关注

    I forgot to initialize the validator validate = validator.New()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?