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

huangapple go评论73阅读模式
英文:

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

问题

我目前正在开发一个功能,可以查看我关注的用户的所有推文。我正在使用Postman进行测试,但是我无法找出问题所在。我知道问题涉及到nil或指针引用,但是尽管我仔细阅读了代码,但还是无法找到问题所在。我对Go语言还比较新,这是我学习的第一种使用这种语法和指针的语言,所以如果有什么明显的问题我没有看到,我提前道歉。

在我的db包中

package db

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

/*
ReadFollowersTweets 读取我关注者的推文
*/

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

}

在路由器中

package routers

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

/*
ReadFollowersTweets 读取所有关注者的推文
*/

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)
}

控制台中的错误

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
英文:

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 (
&quot;context&quot;
&quot;time&quot;
&quot;fmt&quot;
&quot;github.com/JeffersonGarcia15/Twitter-Clone/models&quot;
&quot;go.mongodb.org/mongo-driver/bson&quot;
)
/*
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(&quot;twitter&quot;)
col := db.Collection(&quot;joins&quot;)
skip := (page - 1) * 20
conditions := make([]bson.M, 0)
conditions = append(conditions, bson.M{&quot;$match&quot;: bson.M{&quot;userid&quot;: ID}})
conditions = append(conditions, bson.M{
&quot;$lookup&quot;: bson.M{
&quot;from&quot;:         &quot;tweets&quot;,
&quot;localField&quot;:   &quot;userrelationid&quot;,
&quot;foreignField&quot;: &quot;userid&quot;,
&quot;as&quot;:           &quot;tweets&quot;,
}})
conditions = append(conditions, bson.M{&quot;unwind&quot;: &quot;$tweets&quot;}) //allows all the info to be repeated with the same structure for all tweets on same page
conditions = append(conditions, bson.M{&quot;$sort&quot;: bson.M{&quot;date&quot;: &quot;desc&quot;}})
conditions = append(conditions, bson.M{&quot;$skip&quot;: skip})
conditions = append(conditions, bson.M{&quot;$limit&quot;: 20})
cursor, err := col.Aggregate(ctx, conditions)
var result []models.ReturnFollowersTweets
err := cursor.All(ctx, &amp;result)
if err != nil {
fmt.Println(err.Error())
return result, false
}
return result, true
}

On routers

package routers

import (
&quot;encoding/json&quot;
&quot;net/http&quot;
&quot;strconv&quot;
&quot;github.com/JeffersonGarcia15/Twitter-Clone/db&quot;
)
/*
ReadFollowersTweets reads the tweets of all our followers
*/
func ReadFollowersTweets(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Query().Get(&quot;page&quot;)) &lt; 1 {
http.Error(w, &quot;You must send a page number&quot;, http.StatusBadRequest)
return
}
page, err := strconv.Atoi(r.URL.Query().Get(&quot;page&quot;))
if err != nil {
http.Error(w, &quot;You must send a page number as an int greater than 0&quot;+err.Error(), http.StatusBadRequest)
return
}
response, correct := db.ReadFollowersTweets(IDUser, page)
if !correct {
http.Error(w, &quot;An error occurred when reading the tweets&quot;, http.StatusBadRequest)
return
}
w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
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

答案1

得分: 1

在你的代码中,堆栈跟踪的最后一行是:

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

根据引用的代码,这似乎是:

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

让我们看看,这可能导致nil指针吗?让我们看看相关部分是如何初始化的。

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

你在这里丢弃了一个错误,所以很可能这是你的原因。永远不要丢弃错误,尤其是当某些东西失败而你无法找出原因时。这应该是你首先查找的东西。

英文:

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, &amp;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.

huangapple
  • 本文由 发表于 2021年10月4日 23:20:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/69438481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定