Home > Enterprise >  http: panic serving [::1]:54831: runtime error: invalid memory address or nil pointer dereference
http: panic serving [::1]:54831: runtime error: invalid memory address or nil pointer dereference

Time:10-05

I am currently working on a feature where I will be able to see all the tweets from the users I follow, i am testing it using Postman, but I cannot figure out what the issue is, I know it has to do with a nil or pointer deference, but I haven't been able to figure it out despite the careful readings I have done on my code. I am pretty much new to Go and this is the first language I learn that uses this sort of syntax and that uses pointers so I apologize in advanced if it is something obvious I am not seeing. On my db package

package db

import (
    "context"
    "time"
    "fmt"
    "github.com/JeffersonGarcia15/Twitter-Clone/models"
    "go.mongodb.org/mongo-driver/bson"
)

/*
ReadFollowersTweets reads the tweets from my followers
*/

func ReadFollowersTweets(ID string, page int) ([]models.ReturnFollowersTweets, bool) {
    ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
    defer cancel()

    db := MongoCN.Database("twitter")
    col := db.Collection("joins")

    skip := (page - 1) * 20

    conditions := make([]bson.M, 0)
    conditions = append(conditions, bson.M{"$match": bson.M{"userid": ID}})
    conditions = append(conditions, bson.M{
        "$lookup": bson.M{
            "from":         "tweets",
            "localField":   "userrelationid",
            "foreignField": "userid",
            "as":           "tweets",
        }})
    conditions = append(conditions, bson.M{"unwind": "$tweets"}) //allows all the info to be repeated with the same structure for all tweets on same page
    conditions = append(conditions, bson.M{"$sort": bson.M{"date": "desc"}})
    conditions = append(conditions, bson.M{"$skip": skip})
    conditions = append(conditions, bson.M{"$limit": 20})

    cursor, err := col.Aggregate(ctx, conditions)
    var result []models.ReturnFollowersTweets

    err := cursor.All(ctx, &result)
    if err != nil {
        fmt.Println(err.Error())
        return result, false
    }
    return result, true

}

On routers

package routers

import (
    "encoding/json"
    "net/http"
    "strconv"
    "github.com/JeffersonGarcia15/Twitter-Clone/db"
)

/*
ReadFollowersTweets reads the tweets of all our followers
*/

func ReadFollowersTweets(w http.ResponseWriter, r *http.Request) {
    if len(r.URL.Query().Get("page")) < 1 {
        http.Error(w, "You must send a page number", http.StatusBadRequest)
        return
    }
    page, err := strconv.Atoi(r.URL.Query().Get("page"))
    if err != nil {
        http.Error(w, "You must send a page number as an int greater than 0" err.Error(), http.StatusBadRequest)
        return
    }
    response, correct := db.ReadFollowersTweets(IDUser, page)
    if !correct {
        http.Error(w, "An error occurred when reading the tweets", http.StatusBadRequest)
        return
    }
    
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(response)
}

Error in console

2021/10/04 10:24:46 http: panic serving [::1]:55085: runtime error: invalid memory address or nil pointer dereference
goroutine 164 [running]:
net/http.(*conn).serve.func1()
        /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:1801  0xb9
panic({0x14bbac0, 0x1985c40})
        /usr/local/Cellar/go/1.17/libexec/src/runtime/panic.go:1047  0x266
go.mongodb.org/mongo-driver/mongo.(*Cursor).closeImplicitSession(0x10526ff)
        /Users/jeffersonlopezgarcia/go/pkg/mod/go.mongodb.org/mongo-driver@v1.7.2/mongo/cursor.go:267  0x14
panic({0x14bbac0, 0x1985c40})
        /usr/local/Cellar/go/1.17/libexec/src/runtime/panic.go:1038  0x215
go.mongodb.org/mongo-driver/mongo.(*Cursor).Close(0x0, {0x16755a8, 0xc000416360})
        /Users/jeffersonlopezgarcia/go/pkg/mod/go.mongodb.org/mongo-driver@v1.7.2/mongo/cursor.go:180  0x5f
panic({0x14bbac0, 0x1985c40})
        /usr/local/Cellar/go/1.17/libexec/src/runtime/panic.go:1038  0x215
go.mongodb.org/mongo-driver/mongo.(*Cursor).All(0x0, {0x16755a8, 0xc000416360}, {0x1487380, 0xc00000e600})
        /Users/jeffersonlopezgarcia/go/pkg/mod/go.mongodb.org/mongo-driver@v1.7.2/mongo/cursor.go:209  0x1fe
github.com/JeffersonGarcia15/Twitter-Clone/db.ReadFollowersTweets({0xc0000fc0c0, 0x18}, 0x1)
        /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/db/readFollowersTweets.go:41  0x8c9
github.com/JeffersonGarcia15/Twitter-Clone/routers.ReadFollowersTweets({0x1673cd0, 0xc000588700}, 0xc000684300)
        /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/routers/readFollowersTweets.go:24  0x10a
net/http.HandlerFunc.ServeHTTP(...)
        /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046
github.com/JeffersonGarcia15/Twitter-Clone/middlew.ValidJWT.func1({0x1673cd0, 0xc000588700}, 0xc000684300)
        /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/middlew/validJWT.go:20  0xb2
net/http.HandlerFunc.ServeHTTP(...)
        /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046
github.com/JeffersonGarcia15/Twitter-Clone/middlew.CheckDB.func1({0x1673cd0, 0xc000588700}, 0xc00059a600)
        /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/middlew/checkDB.go:18  0xa9
net/http.HandlerFunc.ServeHTTP(0xc000684200, {0x1673cd0, 0xc000588700}, 0xc0000a2701)
        /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046  0x2f
github.com/gorilla/mux.(*Router).ServeHTTP(0xc0004ba240, {0x1673cd0, 0xc000588700}, 0xc000684100)
        /Users/jeffersonlopezgarcia/go/pkg/mod/github.com/gorilla/mux@v1.8.0/mux.go:210  0x1cf
github.com/rs/cors.(*Cors).Handler.func1({0x1673cd0, 0xc000588700}, 0xc000684100)
        /Users/jeffersonlopezgarcia/go/pkg/mod/github.com/rs/cors@v1.8.0/cors.go:219  0x1bd
net/http.HandlerFunc.ServeHTTP(0xc000559819, {0x1673cd0, 0xc000588700}, 0x106236e)
        /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046  0x2f
net/http.serverHandler.ServeHTTP({0xc00059a450}, {0x1673cd0, 0xc000588700}, 0xc000684100)
        /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2878  0x43b
net/http.(*conn).serve(0xc00031d4a0, {0x16755e0, 0xc00059a2d0})
        /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:1929  0xb08
created by net/http.(*Server).Serve
        /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:3033  0x4e8

CodePudding user response:

The last line from the stack trace that's in your code is:

/Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/db/readFollowersTweets.go:41

That appears to be, from the quoted code:

err := cursor.All(ctx, &result)

Let's see, how could that cause nil pointer? Let's see where the relevant parts are initialized.

cursor, _ := col.Aggregate(ctx, conditions)

You're discarding an error here, so it seems pretty likely this is your cause. Never discard your errors, especially when something is failing and you can't figure out why. That should always be the first thing you look for.

  • Related