Invalid memory address or nil pointer dereference goroutine

I can connect and fetch DB data without using rest api. But when it comes to rest then I get:

2019/03/02 15:25:29 http: panic serving runtime error: invalid memory address or nil pointer dereference
goroutine 4 [running]:
C:/Go/src/net/http/server.go:1746 +0xd7
panic(0x6c5180, 0x947770)
C:/Go/src/runtime/panic.go:513 +0x1c7
database/sql.(*DB).conn(0x0, 0x76f940, 0xc00004a080, 0xc0001b7001, 0x2, 0x30000, 0x2)
C:/Go/src/database/sql/sql.go:1081 +0x41
database/sql.(*DB).query(0x0, 0x76f940, 0xc00004a080, 0x721823, 0x13, 0x0, 0x0, 0x0, 0x6ef801, 0x20, …)
C:/Go/src/database/sql/sql.go:1514 +0x6d
database/sql.(*DB).QueryContext(0x0, 0x76f940, 0xc00004a080, 0x721823, 0x13, 0x0, 0x0, 0x0, 0x6addc0, 0x1, …)
C:/Go/src/database/sql/sql.go:1496 +0xda
database/sql.(*DB).Query(0x0, 0x721823, 0x13, 0x0, 0x0, 0x0, 0x40c17f, 0x80, 0x703660)
C:/Go/src/database/sql/sql.go:1510 +0x89
main.getBooks(0x76f780, 0xc0002a8000, 0xc000294200)
C:/Users/User/go/src/books-list - 1/main.go:100 +0xb6
net/http.HandlerFunc.ServeHTTP(0x734af8, 0x76f780, 0xc0002a8000, 0xc000294200)
C:/Go/src/net/http/server.go:1964 +0x4b*Router).ServeHTTP(0xc000204300, 0x76f780, 0xc0002a8000, 0xc000294000)
c:/users/user/go/src/ +0xd7
net/http.serverHandler.ServeHTTP(0xc00004f040, 0x76f780, 0xc0002a8000, 0xc000294000)
C:/Go/src/net/http/server.go:2741 +0xb2
net/http.(*conn).serve(0xc000284000, 0x76f900, 0xc00028a040)
C:/Go/src/net/http/server.go:1847 +0x64d
created by net/http.(*Server).Serve
C:/Go/src/net/http/server.go:2851 +0x2fc

In the rest method I do exactly the same as without it (for testing it).
And the most interesting part of the above error is why the program serving while in my code I use http.ListenAndServe("localhost:8000", router) ?

When I stoped the program and started in again then I got slightly similar result with the adress And I suppose that every time the port will be different. Actualy every time I request rest api the port in the error is different.

And it seems that the error hapens in rest method on the following line:

rows, err := db.Query(“select * from books”)

because the next line is


and I do not get console output.

Normally when I get this error in a db.Query, its because the books table doesn’t exist or something related to the database itself. I recommend going in to the database management system and checking if the correct database has the table books.

Otherwise, I recommend giving more information about that handler function in the rest API

Are you talking about the read function for your REST API?

Actualy the reason of the issue was nil database object. I would not say the stacktrace is too clear obout it…

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.