Runtime error: invalid memory address or nil pointer dereference whilst trying to read MySQL

Viewed 33

This is my error:

GET /post/1bt5herh66 HTTP/1.1
Host: 127.0.0.1:8080
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Dnt: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0


runtime error: invalid memory address or nil pointer dereference
C:/Program Files/Go/src/runtime/panic.go:260 (0x6cbab5)
        panicmem: panic(memoryError)
C:/Program Files/Go/src/runtime/signal_windows.go:255 (0x6cba85)
        sigpanic: panicmem()
C:/Program Files/Go/src/database/sql/sql.go:1288 (0x767493)
        (*DB).conn: db.mu.Lock()
C:/Program Files/Go/src/database/sql/sql.go:1730 (0x76891c)
        (*DB).query: dc, err := db.conn(ctx, strategy)
C:/Program Files/Go/src/database/sql/sql.go:1708 (0x768799)
        (*DB).QueryContext: rows, err = db.query(ctx, query, args, cachedOrNewConn)
C:/Program Files/Go/src/database/sql/sql.go:1813 (0x769429)
        (*DB).QueryRowContext: rows, err := db.QueryContext(ctx, query, args...)
C:/Program Files/Go/src/database/sql/sql.go:1827 (0x769405)
        (*DB).QueryRow: return db.QueryRowContext(context.Background(), query, args...)
C:/Users/eclipsek20/Desktop/ProjectGATEWAY/main.go:70 (0x9ef07b)
        ReadPost: err := db.QueryRow("SELECT Content FROM posts WHERE id=?", id).Scan(&p.Content)
C:/Users/eclipsek20/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0x9d2741)
        (*Context).Next: c.handlers[c.index](c)
C:/Users/eclipsek20/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/recovery.go:101 (0x9d272c)
        CustomRecoveryWithWriter.func1: c.Next()
C:/Users/eclipsek20/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0x9d1846)
        (*Context).Next: c.handlers[c.index](c)
C:/Users/eclipsek20/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/logger.go:240 (0x9d1829)
        LoggerWithConfig.func1: c.Next()
C:/Users/eclipsek20/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0x9d0950)
        (*Context).Next: c.handlers[c.index](c)
C:/Users/eclipsek20/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:616 (0x9d05b8)
        (*Engine).handleHTTPRequest: c.Next()
C:/Users/eclipsek20/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:572 (0x9d027c)
        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
C:/Program Files/Go/src/net/http/server.go:2947 (0x8b76eb)
        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
C:/Program Files/Go/src/net/http/server.go:1991 (0x8b3dc6)
        (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
C:/Program Files/Go/src/runtime/asm_amd64.s:1594 (0x6e6320)
        goexit: BYTE    $0x90   // NOP

This is the function I am trying to call:

func ReadPost(c *gin.Context) {
    // Read post from mysql database
    var p Post
    id := c.Param("id")
    err := db.QueryRow("SELECT * FROM posts WHERE id=?", id).Scan(&p.ID, &p.Time, &p.Username, &p.Content)
    if err != nil {
        c.JSON(404, gin.H{
            "message": "Post not found!",
        })
    } else {
        c.JSON(200, gin.H{
            "message": "Post Found!",
            "post":    p,
        })
    }

}

I have spent 6-7h~ up to this point, trying to make it work however to no avail. I have tried using SQLx, using a variety of different SQL drivers and reading the whole table however this did not bring any postive result. EDIT: Here is the initiator code along with the start:

package main

import (
    "database/sql"
    "fmt"
    "log"

    "github.com/gin-gonic/gin"
    _ "github.com/go-sql-driver/mysql"
)

type Post struct {
    ID       int    `json:"id"`
    Time     int    `json:"time"`
    Username string `json:"username"`
    Content  string `json:"content"`
}

var db *sql.DB

func init() {
    // initsql.ConnectToDB()
    db, err := sql.Open("mysql", "root:sSXdG8XRTCMymD8eMq2md5nkN9WjZRkCkLYX3vG6Xb4gjjrteN3w5PhyUQFeG39d@tcp(127.0.0.1:3306)/projectgo?parseTime=true")
    if err != nil {
        log.Fatal("Failed to connect to database. ERROR:", err)
    } else {
        fmt.Println("Connection to DB, Successful.", db)
    }
}

Also as noted in the comments the value is nil whenever it goes to the function, so how do I assign it?

0 Answers
Related