登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-19 21:00:37 478浏览 收藏

在处理 Go 应用程序中的运行时错误时,无效的内存地址或空指针取消引用经常会令人困惑。通常,此类错误源于对 nil 指针或无效内存地址的处理。虽然问题可能存在于代码的不同部分,但特别需要注意处理 HTTP 请求正文的情况。 如果请求正文为 nil,则表明请求没有正文,例如 GET 请求。然而,对于服务器请求,正文始终非空。因此,当使用 json.Decoder 解码服务器请求正文时,必须确保将非 nil 指针传递给 Decode 方法。否则,会引发无效内存地址或空指针取消引用的错误。

问题内容

新手 go 编程时遇到问题,例如:无效的内存地址或 nil 指针取消引用

有时我可以解决问题,但这让我感到困惑。 这是处理程序级别的代码,我尝试实现 ###p.repo.updateprofile() 和来自 r.body 解码的数据

//updateprofile handler
func (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
}

mycode 在数据库中运行良好,数据已成功更新,但响应服务器为

panic: runtime error: invalid memory address or nil pointer dereference
2019/07/21 13:27:36 goroutine 8 [running]:
runtime/debug.Stack(0xc00028e100, 0x16b1a20, 0xc000094040)
    /usr/local/Cellar/go/1.12.6/libexec/src/runtime/debug/stack.go:24 +0x9d
github.com/go-chi/chi/middleware.Recoverer.func1.1(0xc00028e100, 0x16b6be0, 0xc000256280)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/middleware/recoverer.go:25 +0x9c
panic(0x155e7a0, 0x1a66a10)
    /usr/local/Cellar/go/1.12.6/libexec/src/runtime/panic.go:522 +0x1b5
audioo_api/handler.(*Profile).UpdateProfile(0xc000020030, 0x16b6be0, 0xc000256280, 0xc00028e200)
    /Users/rizaldinurmuhammad/go/src/audioo_api/handler/profile.go:73 +0x524
net/http.HandlerFunc.ServeHTTP(0xc000020050, 0x16b6be0, 0xc000256280, 0xc00028e200)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
audioo_api/lib/mid.Authenticate.func1.1(0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/audioo_api/lib/mid/auth.go:48 +0x71e
net/http.HandlerFunc.ServeHTTP(0xc00000e0a0, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/chi.(*ChainHandler).ServeHTTP(0xc000066140, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/chain.go:31 +0x52
github.com/go-chi/chi.(*Mux).routeHTTP(0xc0000a5f80, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/mux.go:425 +0x27f
net/http.HandlerFunc.ServeHTTP(0xc000020040, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/chi.(*Mux).ServeHTTP(0xc0000a5f80, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/mux.go:70 +0x451
github.com/go-chi/chi.(*Mux).Mount.func1(0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/mux.go:292 +0x127
net/http.HandlerFunc.ServeHTTP(0xc00000e0e0, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/chi.(*Mux).routeHTTP(0xc0000a59e0, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/mux.go:425 +0x27f
net/http.HandlerFunc.ServeHTTP(0xc0001db880, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/chi.(*Mux).ServeHTTP(0xc0000a59e0, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/mux.go:70 +0x451
github.com/go-chi/chi.(*Mux).Mount.func1(0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/mux.go:292 +0x127
net/http.HandlerFunc.ServeHTTP(0xc00000e180, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/chi.(*Mux).routeHTTP(0xc0000a5920, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/mux.go:425 +0x27f
net/http.HandlerFunc.ServeHTTP(0xc000020090, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
audioo_api/lib/mid.Limit.func1(0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/audioo_api/lib/mid/limit.go:79 +0xe5
net/http.HandlerFunc.ServeHTTP(0xc00000e1a0, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/cors.(*Cors).Handler.func1(0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/cors/cors.go:201 +0x1a4
net/http.HandlerFunc.ServeHTTP(0xc00000e1c0, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/chi/middleware.Recoverer.func1(0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/middleware/recoverer.go:35 +0x9f
net/http.HandlerFunc.ServeHTTP(0xc00000e1e0, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/chi/middleware.RedirectSlashes.func1(0x16b6be0, 0xc000256280, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/middleware/strip.go:53 +0x202
net/http.HandlerFunc.ServeHTTP(0xc00000e200, 0x16b6be0, 0xc000256280, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/chi/middleware.(*Compressor).Handler.func1.1(0x1f69180, 0xc000256240, 0xc00028e100)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/middleware/compress.go:190 +0x254
net/http.HandlerFunc.ServeHTTP(0xc00000e2c0, 0x1f69180, 0xc000256240, 0xc00028e100)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/chi/middleware.RequestLogger.func1.1(0x16b78a0, 0xc000226000, 0xc00028e000)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/middleware/logger.go:46 +0x291
net/http.HandlerFunc.ServeHTTP(0xc00009a210, 0x16b78a0, 0xc000226000, 0xc00028e000)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1995 +0x44
github.com/go-chi/chi.(*Mux).ServeHTTP(0xc0000a5920, 0x16b78a0, 0xc000226000, 0xc000154000)
    /Users/rizaldinurmuhammad/go/src/github.com/go-chi/chi/mux.go:82 +0x294
net/http.serverHandler.ServeHTTP(0xc00009c410, 0x16b78a0, 0xc000226000, 0xc000154000)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:2774 +0xa8
net/http.(*conn).serve(0xc0002ce640, 0x16b8aa0, 0xc000067340)
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:1878 +0x851
created by net/http.(*Server).Serve
    /usr/local/Cellar/go/1.12.6/libexec/src/net/http/server.go:2884 +0x2f4

我尝试更改上下文来实现数据库,但响应仍然相同。

我想知道这个问题与r.body相关,但我不知道如何弄清楚


解决方案


根据 body io.readcloser 的包文档:

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

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

datanil 指针,&data 是指向 nil 指针的指针。

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

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

如果 data 是一个接口,首先为其分配一个实际值,然后再次在不引用 decode 的情况下传递: errdecode := json.newdecoder(r.body).decode(data)

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

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《恐慌:处理运行时错误时遇到的无效内存地址或零指针取消引用 || r.身体模型》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>