-2

i have controller.go:

package controller
import (
    "github.com/fishkaoff/todoList/pkg/postgresql"
    "github.com/gin-gonic/gin"
    "net/http"
    "context"
)

type Task struct {
    Title string 
    Description string
 }


func GetTasks(c *gin.Context) {
    var response *Task
    err := db.Conn.QueryRow(context.Background(), "select * from tasks").Scan(&response.Title, 
    &response.Description)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error":"error"})
    }

    c.JSON(200, gin.H{
        "page":"gettasks",
        "tasks": response,
    })
}

when i am sending request it returns me

```runtime error: invalid memory address or nil pointer dereference
C:/Program Files/Go/src/runtime/panic.go:260 (0xb7bab5)
        panicmem: panic(memoryError)
C:/Program Files/Go/src/runtime/signal_windows.go:255 (0xb7ba85)
        sigpanic: panicmem()
D:/workspace/golangWWW/pkg/mod/github.com/jackc/pgx/v4@v4.17.2/conn.go:551 (0x1015db1)
        (*Conn).Query: simpleProtocol := c.config.PreferSimpleProtocol
D:/workspace/golangWWW/pkg/mod/github.com/jackc/pgx/v4@v4.17.2/conn.go:663 (0x101b9dc)
        (*Conn).QueryRow: rows, _ := c.Query(ctx, sql, args...)
D:/workspace/golangWWW/todolist/internal/controller/controller.go:17 (0x101b9ab)
        GetTasks: err := db.Conn.QueryRow(context.Background(), "select * from tasks").Scan(&response.Title, &response.Description)
D:/workspace/golangWWW/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0xeb99c1)
        (*Context).Next: c.handlers[c.index](c)
D:/workspace/golangWWW/pkg/mod/github.com/gin-gonic/gin@v1.8.1/recovery.go:101 (0xeb99ac)
        CustomRecoveryWithWriter.func1: c.Next()
D:/workspace/golangWWW/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0xeb8ac6)
        (*Context).Next: c.handlers[c.index](c)
D:/workspace/golangWWW/pkg/mod/github.com/gin-gonic/gin@v1.8.1/logger.go:240 (0xeb8aa9)
        LoggerWithConfig.func1: c.Next()
D:/workspace/golangWWW/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0xeb7bd0)
        (*Context).Next: c.handlers[c.index](c)
D:/workspace/golangWWW/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:616 (0xeb7838)
        (*Engine).handleHTTPRequest: c.Next()
D:/workspace/golangWWW/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:572 (0xeb74fc)
        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
C:/Program Files/Go/src/net/http/server.go:2947 (0xd70feb)
        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
C:/Program Files/Go/src/net/http/server.go:1991 (0xd6d6c6)
        (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
C:/Program Files/Go/src/runtime/asm_amd64.s:1594 (0xb96320)
        goexit: BYTE    $0x90   // NOP```

db.Conn is imported from db.go:

    package db


    import (
        "os"
        "fmt"
        "context"


        "github.com/jackc/pgx/v4/"
        "github.com/fishkaoff/todoList/internal/config"
    )

    var Conn *pgx.Conn

    func InitDatabase(config config.Config) {
        Conn, err := pgx.Connect(context.Background(), config.DBUrl)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
            os.Exit(1)
        }
        defer Conn.Close()
    }

InitDatabase is calling in main.go


in database table and columns are created


i am using pgx v4


P.S: sorry for my bad english, i am not a native speaker ⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣_________________________________________________________ ⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣

fishkaoff
  • 19
  • 3
  • please don't paste text as a screenshot. Copy the code out of the terminal and past e as text between "```" and "```" at beginning and end to crete a text block. – erik258 Sep 17 '22 at 14:28
  • 1
    @DanielFarrell, edited, i think now it is correctly – fishkaoff Sep 17 '22 at 15:34
  • 1
    `db.Conn` is nil. – Charlie Tumahai Sep 17 '22 at 15:57
  • @CeriseLimón, sry, updated ,check again pls) – fishkaoff Sep 17 '22 at 16:28
  • InitDatabase assigns to function local variable Conn, not to the package-level variable with the same name. Remove the [short variable declaration](https://go.dev/ref/spec#Short_variable_declarations) for Conn: `var err error; Conn, err = pgx.Connect(context.Background(), config.DBUrl)`. Also, InitDatabase close the connection. Remove `defer Conn.Close()`. – Charlie Tumahai Sep 17 '22 at 16:36
  • thank you! it solved my problem combined with the answer below – fishkaoff Sep 17 '22 at 16:58
  • 1
    Please please always start with using your favorite internet search engine to search for the error text before rushing to StackOverflow (or a similar resource). Searching for "runtime error: invalid memory address or nil pointer dereference" would have brought before you literally millions of results from which you could learn what this error is about, how to understand from the stack trace which follows it where the error is, and what are the likely causes. There was simply no reason to create yet another question on SO asking about the problem which has been discussed thousand times already. – kostix Sep 17 '22 at 17:47

1 Answers1

2
    var response *Task

You have allocated memory to store a *Task, not a Task.

Then when you

    .Scan(&response.Title,     &response.Description)

Attempt to take the address of response.Title and response.Description. These fields don't have an address because response is a pointer but doesn't point to a valid task.

Try:

var response Task

Now you actually have allocated space for the Title and Description fields and thus have somewhere to store those values.

erik258
  • 14,701
  • 2
  • 25
  • 31