-4
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

lab0
  • 199
  • 1
  • 2
  • 10

1 Answers1

2

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.

Adrian
  • 42,911
  • 6
  • 107
  • 99