为了账号安全,请及时绑定邮箱和手机立即绑定

恐慌:运行时错误:无效的内存地址或零指针取消引用 || r.身体模型

恐慌:运行时错误:无效的内存地址或零指针取消引用 || r.身体模型

Go
慕运维8079593 2023-07-04 19:05:07
我的 Go 编程新手遇到问题,例如:无效的内存地址或 nil 指针取消引用有时我可以解决问题,但这让我感到困惑。这是处理程序级别的代码,我尝试实现 ###p.repo.UpdateProfile() 和来自 r.body 解码的数据//UpdateProfile handlerfunc (p *Profile) UpdateProfile(w http.ResponseWriter, r *http.Request) {    var (        errForm   models.ErrorForm        resp      models.Response        respError models.ErrorResponse        errField  models.ErrField        data      *models.EditProfile    )    userid := r.Context().Value(viper.GetString("token.userid"))                errDecode := json.NewDecoder(r.Body).Decode(&data)    errPayload := p.repo.UpdateProfile(r.Context(), data, userid)    if errPayload.Error() == "username_exist" {        respError.Message = "username already taken"        respError.Status = 422        lib.ResJSON(w, respError.Status, respError)        return    }    lib.Catch(errPayload)    resp.Data = ""    resp.Message = "Success"    resp.Status = 200    lib.ResJSON(w, resp.Status, resp)}和方法如下:func (m *mysqlProfileRepo) UpdateProfile(ctx context.Context, p *models.EditProfile, userid interface{}) error {    query := ""    var checkexist int    row1, err1 := m.Conn.QueryContext(ctx, query, p.Username)    if err1 != nil {        return err1    }    for row1.Next() {        if errSc1 := row1.Scan(&checkexist); errSc1 != nil {            return errors.New("error_scan_db")        }    }    if checkexist != 0 {        return errors.New("username_exist")    }    query1 := ""    query2 := ""    stmts := []*lib.PipelineStmt{        lib.NewPipelineStmt(query1, p.Image, p.Location, p.Link, p.Bio, p.Birthday, userid),        lib.NewPipelineStmt(query2, p.Username, p.Fullname, userid),    }    errTrx := lib.WithTransaction(m.Conn, func(tx lib.Transaction) error {        _, errRunPipe := lib.RunPipeline(tx, stmts...)        return errRunPipe    })    if errTrx != nil {        return errTrx    }    return nil}
查看完整描述

1 回答

?
慕森卡

TA贡献1806条经验 获得超8个赞

根据 Body io.ReadCloser 的包文档:

对于客户端请求,nil body 意味着该请求没有 body,例如 GET 请求。对于服务器请求,请求正文始终不为零。

你说,它是一个服务器,所以,它总是非零,因此错误出现在Decode你将指针传递给零指针的调用中。

data是一个nil指针,&data是一个指向nil指针的指针。

如果数据是非接口类型,除非models包明确禁止,否则解决方案new(EditProfile)

    data = new(models.EditProfile)
    errDecode := json.NewDecoder(r.Body).Decode(data)

如果 data 是一个接口,则首先为其分配一个实际值,然后再次传递而不引用DecodeerrDecode := json.NewDecoder(r.Body).Decode(data)

在后一种情况下,还要仔细检查您是否声明了正确的类型*models.EditProfile


查看完整回答
反对 回复 2023-07-04
  • 1 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信