doue1925 2018-07-19 18:41
浏览 497
已采纳

Golang错误“无效的内存地址或nil指针取消引用”,为什么会发生这种情况? [重复]

This question already has an answer here:

package main

import (
        "fmt"
        "net/http"
)

func main() {
        http.HandleFunc("/", handler)
        http.HandleFunc("/cookie", cookie)
        http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
            // do ...
}

func cookie(w http.ResponseWriter, r *http.Request) {
        cd, _ := r.Cookie("hello")

        if cd.Value == "username" {
               // do ...
        }
}

if run:

$ go run main.go

no problem server is work, but in firfox when inserting "/cookie" path the problem occurs.

Error:

runtime error: invalid memory address or nil pointer dereference

</div>
  • 写回答

1条回答 默认 最新

  • drmeu26880 2018-07-19 18:47
    关注

    This occurs, as the error message says, when you try to dereference (use) nil. Without knowing which line the error was reported on, I would have to guess it's here:

        cd, _ := r.Cookie("hello")
    
        if cd.Value == "username" {  // <-- This line
               // do ...
        }
    

    Because you're discarding the error from r.Cookie() instead of checking the error, so you don't know that the cookie hello doesn't exist, meaning cd is nil. So when you try to use cd.Value, you're dereferencing a nil pointer, causing the panic you're seeing.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog