dprfe04886 2017-10-08 06:08
浏览 47
已采纳

紧急服务[:: 1]:46738:运行时错误:无效的内存地址或nil指针取消引用

Can someone explain what's happening? Is there something I might be missing? I am new to Go. I am making a simple CRUD application, it compiles ok, but when I start the server, it gives me an runtime error.

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

my main.go file is on github.

  • 写回答

1条回答 默认 最新

  • douzhenggui8171 2017-10-08 06:13
    关注

    The call to ParseFiles returns nil and an error. The call to t.Execute panics because t is nil.

    To avoid the panic, return from the handler after calling http.Error.

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

    It's not a good idea to send error messages with possible implementation details to the client. I suggest the following:

    ...
    t, err := template.ParseFiles("index.html")
    
    if err != nil {
        log.Println(err)
        http.Error(w, "Internal server error", http.StatusInternalServerError)
        return  
    }
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 相同型号电脑与配置,发现主板有一台貌似缺少了好多元器件似的,会影响稳定性和使用寿命吗?
    • ¥15 要求编写稀疏矩阵A的转置矩阵的算法
    • ¥15 编写满足以下要求的停车场管理程序,设停车场只有一个可停放n辆车的狭窄通道且只有一个大门可供车辆进出。
    • ¥20 powerbulider 导入excel文件,显示不完整
    • ¥15 用keil调试程序保证结果进行led相关闪烁
    • ¥15 paddle训练自己的数据loss降不下去
    • ¥20 用matlab的pdetool解决以下三个问题
    • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
    • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
    • ¥20 h3c静态路要求有详细过程