oschwald/geoip2-golang

runtime error: invalid memory address or nil pointer dereference

opotemkin opened this issue · 2 comments

I have a structure:

// ....

var db *geoip2.Reader

// ....

func GetLocation(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	// ....

	record, err := db.City(net.ParseIP(ip))
	if err != nil {
		log.Fatal(err)
	}

	// ....

}

func main() {
	// ....

	db, err := geoip2.Open("/usr/share/GeoIP/GeoIP2-City.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// ....
	r.HandleFunc("/get-location/{ip}", GetLocation).Methods("GET")
       // ....
	
}

And I create request:

curl -X GET http://localhost:8000/get-location/81.2.69.142

End response:

2019/03/06 12:16:13 http: panic serving 127.0.0.1:47474: runtime error: invalid memory address or nil pointer dereference
goroutine 21 [running]:
net/http.(*conn).serve.func1(0xc00009cfa0)
	/usr/local/go/src/net/http/server.go:1746 +0xd0
panic(0x6c2160, 0x94aae0)
	/usr/local/go/src/runtime/panic.go:513 +0x1b9
github.com/oschwald/geoip2-golang.(*Reader).City(0x0, 0xc00015bae0, 0x10, 0x10, 0x10, 0xc0000b5048, 0x0)
	/home/oleg/Documents/html/go/src/github.com/oschwald/geoip2-golang/reader.go:241 +0x37
main.GetLocation(0x76ad80, 0xc0003c4000, 0xc00044a800)
	/home/oleg/Documents/html/oblivki/localgeo/main.go:140 +0x1e7
net/http.HandlerFunc.ServeHTTP(0x72e9f0, 0x76ad80, 0xc0003c4000, 0xc00044a800)
	/usr/local/go/src/net/http/server.go:1964 +0x44
github.com/gorilla/mux.(*Router).ServeHTTP(0xc0001180c0, 0x76ad80, 0xc0003c4000, 0xc00044a500)
	/home/oleg/Documents/html/go/src/github.com/gorilla/mux/mux.go:212 +0xd0
net/http.serverHandler.ServeHTTP(0xc0000865b0, 0x76ad80, 0xc0003c4000, 0xc00044a500)
	/usr/local/go/src/net/http/server.go:2741 +0xab
net/http.(*conn).serve(0xc00009cfa0, 0x76b000, 0xc0000941c0)
	/usr/local/go/src/net/http/server.go:1847 +0x646
created by net/http.(*Server).Serve
	/usr/local/go/src/net/http/server.go:2851 +0x2f5

Based on the stack trace, it appears db is nil when you call City. I'd guess because you are declaring a new variable db in main, shadowing the original one.

Closing due to lack of response.