【问题标题】:panic serving [::1]:46738: runtime error: invalid memory address or nil pointer dereference恐慌服务 [::1]:46738: 运行时错误: 无效的内存地址或 nil 指针取消引用
【发布时间】:2017-10-08 06:08:46
【问题描述】:

有人可以解释发生了什么吗?有什么我可能会丢失的吗?我是 Go 新手。我正在制作一个简单的 CRUD 应用程序,它可以编译,但是当我启动服务器时,它给了我一个运行时错误。

2017/10/08 11:11:59 http: multiple response.WriteHeader calls
2017/10/08 11:11:59 http: panic serving [::1]:46828: runtime error: invalid memory address or nil pointer dereference
goroutine 19 [running]:
net/http.(*conn).serve.func1(0xc42008ce60)
    /home/vikram/go/src/net/http/server.go:1697 +0xd0
panic(0x740160, 0x97cc10)
    /home/vikram/go/src/runtime/panic.go:491 +0x283
html/template.(*Template).escape(0x0, 0x0, 0x0)
    /home/vikram/go/src/html/template/template.go:95 +0x38
html/template.(*Template).Execute(0x0, 0x94d920, 0xc420186000, 0x719e00, 0x9ab500, 0xc4201820c0, 0x0)
    /home/vikram/go/src/html/template/template.go:119 +0x2f
main.indexHandler(0x9519e0, 0xc420186000, 0xc420160100)
    /home/vikram/Projects/golang/src/github.com/vikramdurai/blog-app-go/main.go:188 +0x185
net/http.HandlerFunc.ServeHTTP(0x7b8da8, 0x9519e0, 0xc420186000, 0xc420160100)
    /home/vikram/go/src/net/http/server.go:1918 +0x44
net/http.(*ServeMux).ServeHTTP(0x98ad20, 0x9519e0, 0xc420186000, 0xc420160100)
    /home/vikram/go/src/net/http/server.go:2254 +0x130
net/http.serverHandler.ServeHTTP(0xc420087110, 0x9519e0, 0xc420186000, 0xc420160100)
    /home/vikram/go/src/net/http/server.go:2619 +0xb4
net/http.(*conn).serve(0xc42008ce60, 0x9520a0, 0xc42007c280)
    /home/vikram/go/src/net/http/server.go:1801 +0x71d
created by net/http.(*Server).Serve
    /home/vikram/go/src/net/http/server.go:2720 +0x288

我的main.go 文件位于github

【问题讨论】:

    标签: go


    【解决方案1】:

    ParseFiles 的调用返回nil 和一个错误。对 t.Execute 的调用会发生恐慌,因为 t 是 nil。

    为避免恐慌,请在调用 http.Error 后从处理程序返回。

    ...
    t, err := template.ParseFiles("index.html")
    
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return  
    }
    ...
    

    向客户端发送带有可能实现细节的错误消息不是一个好主意。我建议如下:

    ...
    t, err := template.ParseFiles("index.html")
    
    if err != nil {
        log.Println(err)
        http.Error(w, "Internal server error", http.StatusInternalServerError)
        return  
    }
    ...
    

    【讨论】:

    • 我发送错误是因为我在开发环境中。 当然 我将删除生产中的错误报告。不过谢谢回答! :)
    猜你喜欢
    • 2015-02-24
    • 2022-01-05
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 2016-12-12
    • 2013-04-23
    • 2019-03-09
    • 2023-01-11
    相关资源
    最近更新 更多