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

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

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

问题

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

在我的db包中

  1. package db
  2. import (
  3. "context"
  4. "time"
  5. "fmt"
  6. "github.com/JeffersonGarcia15/Twitter-Clone/models"
  7. "go.mongodb.org/mongo-driver/bson"
  8. )
  9. /*
  10. ReadFollowersTweets 读取我关注者的推文
  11. */
  12. func ReadFollowersTweets(ID string, page int) ([]models.ReturnFollowersTweets, bool) {
  13. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  14. defer cancel()
  15. db := MongoCN.Database("twitter")
  16. col := db.Collection("joins")
  17. skip := (page - 1) * 20
  18. conditions := make([]bson.M, 0)
  19. conditions = append(conditions, bson.M{"$match": bson.M{"userid": ID}})
  20. conditions = append(conditions, bson.M{
  21. "$lookup": bson.M{
  22. "from": "tweets",
  23. "localField": "userrelationid",
  24. "foreignField": "userid",
  25. "as": "tweets",
  26. }})
  27. conditions = append(conditions, bson.M{"unwind": "$tweets"}) //allows all the info to be repeated with the same structure for all tweets on same page
  28. conditions = append(conditions, bson.M{"$sort": bson.M{"date": "desc"}})
  29. conditions = append(conditions, bson.M{"$skip": skip})
  30. conditions = append(conditions, bson.M{"$limit": 20})
  31. cursor, err := col.Aggregate(ctx, conditions)
  32. var result []models.ReturnFollowersTweets
  33. err := cursor.All(ctx, &result)
  34. if err != nil {
  35. fmt.Println(err.Error())
  36. return result, false
  37. }
  38. return result, true
  39. }

在路由器中

  1. package routers
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strconv"
  6. "github.com/JeffersonGarcia15/Twitter-Clone/db"
  7. )
  8. /*
  9. ReadFollowersTweets 读取所有关注者的推文
  10. */
  11. func ReadFollowersTweets(w http.ResponseWriter, r *http.Request) {
  12. if len(r.URL.Query().Get("page")) < 1 {
  13. http.Error(w, "You must send a page number", http.StatusBadRequest)
  14. return
  15. }
  16. page, err := strconv.Atoi(r.URL.Query().Get("page"))
  17. if err != nil {
  18. http.Error(w, "You must send a page number as an int greater than 0"+err.Error(), http.StatusBadRequest)
  19. return
  20. }
  21. response, correct := db.ReadFollowersTweets(IDUser, page)
  22. if !correct {
  23. http.Error(w, "An error occurred when reading the tweets", http.StatusBadRequest)
  24. return
  25. }
  26. w.Header().Set("Content-Type", "application/json")
  27. w.WriteHeader(http.StatusCreated)
  28. json.NewEncoder(w).Encode(response)
  29. }

控制台中的错误

  1. 2021/10/04 10:24:46 http: panic serving [::1]:55085: runtime error: invalid memory address or nil pointer dereference
  2. goroutine 164 [running]:
  3. net/http.(*conn).serve.func1()
  4. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:1801 +0xb9
  5. panic({0x14bbac0, 0x1985c40})
  6. /usr/local/Cellar/go/1.17/libexec/src/runtime/panic.go:1047 +0x266
  7. go.mongodb.org/mongo-driver/mongo.(*Cursor).closeImplicitSession(0x10526ff)
  8. /Users/jeffersonlopezgarcia/go/pkg/mod/go.mongodb.org/mongo-driver@v1.7.2/mongo/cursor.go:267 +0x14
  9. panic({0x14bbac0, 0x1985c40})
  10. /usr/local/Cellar/go/1.17/libexec/src/runtime/panic.go:1038 +0x215
  11. go.mongodb.org/mongo-driver/mongo.(*Cursor).Close(0x0, {0x16755a8, 0xc000416360})
  12. /Users/jeffersonlopezgarcia/go/pkg/mod/go.mongodb.org/mongo-driver@v1.7.2/mongo/cursor.go:180 +0x5f
  13. panic({0x14bbac0, 0x1985c40})
  14. /usr/local/Cellar/go/1.17/libexec/src/runtime/panic.go:1038 +0x215
  15. go.mongodb.org/mongo-driver/mongo.(*Cursor).All(0x0, {0x16755a8, 0xc000416360}, {0x1487380, 0xc00000e600})
  16. /Users/jeffersonlopezgarcia/go/pkg/mod/go.mongodb.org/mongo-driver@v1.7.2/mongo/cursor.go:209 +0x1fe
  17. github.com/JeffersonGarcia15/Twitter-Clone/db.ReadFollowersTweets({0xc0000fc0c0, 0x18}, 0x1)
  18. /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/db/readFollowersTweets.go:41 +0x8c9
  19. github.com/JeffersonGarcia15/Twitter-Clone/routers.ReadFollowersTweets({0x1673cd0, 0xc000588700}, 0xc000684300)
  20. /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/routers/readFollowersTweets.go:24 +0x10a
  21. net/http.HandlerFunc.ServeHTTP(...)
  22. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046
  23. github.com/JeffersonGarcia15/Twitter-Clone/middlew.ValidJWT.func1({0x1673cd0, 0xc000588700}, 0xc000684300)
  24. /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/middlew/validJWT.go:20 +0xb2
  25. net/http.HandlerFunc.ServeHTTP(...)
  26. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046
  27. github.com/JeffersonGarcia15/Twitter-Clone/middlew.CheckDB.func1({0x1673cd0, 0xc000588700}, 0xc00059a600)
  28. /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/middlew/checkDB.go:18 +0xa9
  29. net/http.HandlerFunc.ServeHTTP(0xc000684200, {0x1673cd0, 0xc000588700}, 0xc0000a2701)
  30. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046 +0x2f
  31. github.com/gorilla/mux.(*Router).ServeHTTP(0xc0004ba240, {0x1673cd0, 0xc000588700}, 0xc000684100)
  32. /Users/jeffersonlopezgarcia/go/pkg/mod/github.com/gorilla/mux@v1.8.0/mux.go:210 +0x1cf
  33. github.com/rs/cors.(*Cors).Handler.func1({0x1673cd0, 0xc000588700}, 0xc000684100)
  34. /Users/jeffersonlopezgarcia/go/pkg/mod/github.com/rs/cors@v1.8.0/cors.go:219 +0x1bd
  35. net/http.HandlerFunc.ServeHTTP(0xc000559819, {0x1673cd0, 0xc000588700}, 0x106236e)
  36. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046 +0x2f
  37. net/http.serverHandler.ServeHTTP({0xc00059a450}, {0x1673cd0, 0xc000588700}, 0xc000684100)
  38. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2878 +0x43b
  39. net/http.(*conn).serve(0xc00031d4a0, {0x16755e0, 0xc00059a2d0})
  40. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:1929 +0xb08
  41. created by net/http.(*Server).Serve
  42. /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

  1. package db
  2. import (
  3. &quot;context&quot;
  4. &quot;time&quot;
  5. &quot;fmt&quot;
  6. &quot;github.com/JeffersonGarcia15/Twitter-Clone/models&quot;
  7. &quot;go.mongodb.org/mongo-driver/bson&quot;
  8. )
  9. /*
  10. ReadFollowersTweets reads the tweets from my followers
  11. */
  12. func ReadFollowersTweets(ID string, page int) ([]models.ReturnFollowersTweets, bool) {
  13. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  14. defer cancel()
  15. db := MongoCN.Database(&quot;twitter&quot;)
  16. col := db.Collection(&quot;joins&quot;)
  17. skip := (page - 1) * 20
  18. conditions := make([]bson.M, 0)
  19. conditions = append(conditions, bson.M{&quot;$match&quot;: bson.M{&quot;userid&quot;: ID}})
  20. conditions = append(conditions, bson.M{
  21. &quot;$lookup&quot;: bson.M{
  22. &quot;from&quot;: &quot;tweets&quot;,
  23. &quot;localField&quot;: &quot;userrelationid&quot;,
  24. &quot;foreignField&quot;: &quot;userid&quot;,
  25. &quot;as&quot;: &quot;tweets&quot;,
  26. }})
  27. 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
  28. conditions = append(conditions, bson.M{&quot;$sort&quot;: bson.M{&quot;date&quot;: &quot;desc&quot;}})
  29. conditions = append(conditions, bson.M{&quot;$skip&quot;: skip})
  30. conditions = append(conditions, bson.M{&quot;$limit&quot;: 20})
  31. cursor, err := col.Aggregate(ctx, conditions)
  32. var result []models.ReturnFollowersTweets
  33. err := cursor.All(ctx, &amp;result)
  34. if err != nil {
  35. fmt.Println(err.Error())
  36. return result, false
  37. }
  38. return result, true
  39. }

On routers

package routers

  1. import (
  2. &quot;encoding/json&quot;
  3. &quot;net/http&quot;
  4. &quot;strconv&quot;
  5. &quot;github.com/JeffersonGarcia15/Twitter-Clone/db&quot;
  6. )
  7. /*
  8. ReadFollowersTweets reads the tweets of all our followers
  9. */
  10. func ReadFollowersTweets(w http.ResponseWriter, r *http.Request) {
  11. if len(r.URL.Query().Get(&quot;page&quot;)) &lt; 1 {
  12. http.Error(w, &quot;You must send a page number&quot;, http.StatusBadRequest)
  13. return
  14. }
  15. page, err := strconv.Atoi(r.URL.Query().Get(&quot;page&quot;))
  16. if err != nil {
  17. http.Error(w, &quot;You must send a page number as an int greater than 0&quot;+err.Error(), http.StatusBadRequest)
  18. return
  19. }
  20. response, correct := db.ReadFollowersTweets(IDUser, page)
  21. if !correct {
  22. http.Error(w, &quot;An error occurred when reading the tweets&quot;, http.StatusBadRequest)
  23. return
  24. }
  25. w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
  26. w.WriteHeader(http.StatusCreated)
  27. json.NewEncoder(w).Encode(response)
  28. }

Error in console

  1. 2021/10/04 10:24:46 http: panic serving [::1]:55085: runtime error: invalid memory address or nil pointer dereference
  2. goroutine 164 [running]:
  3. net/http.(*conn).serve.func1()
  4. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:1801 +0xb9
  5. panic({0x14bbac0, 0x1985c40})
  6. /usr/local/Cellar/go/1.17/libexec/src/runtime/panic.go:1047 +0x266
  7. go.mongodb.org/mongo-driver/mongo.(*Cursor).closeImplicitSession(0x10526ff)
  8. /Users/jeffersonlopezgarcia/go/pkg/mod/go.mongodb.org/mongo-driver@v1.7.2/mongo/cursor.go:267 +0x14
  9. panic({0x14bbac0, 0x1985c40})
  10. /usr/local/Cellar/go/1.17/libexec/src/runtime/panic.go:1038 +0x215
  11. go.mongodb.org/mongo-driver/mongo.(*Cursor).Close(0x0, {0x16755a8, 0xc000416360})
  12. /Users/jeffersonlopezgarcia/go/pkg/mod/go.mongodb.org/mongo-driver@v1.7.2/mongo/cursor.go:180 +0x5f
  13. panic({0x14bbac0, 0x1985c40})
  14. /usr/local/Cellar/go/1.17/libexec/src/runtime/panic.go:1038 +0x215
  15. go.mongodb.org/mongo-driver/mongo.(*Cursor).All(0x0, {0x16755a8, 0xc000416360}, {0x1487380, 0xc00000e600})
  16. /Users/jeffersonlopezgarcia/go/pkg/mod/go.mongodb.org/mongo-driver@v1.7.2/mongo/cursor.go:209 +0x1fe
  17. github.com/JeffersonGarcia15/Twitter-Clone/db.ReadFollowersTweets({0xc0000fc0c0, 0x18}, 0x1)
  18. /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/db/readFollowersTweets.go:41 +0x8c9
  19. github.com/JeffersonGarcia15/Twitter-Clone/routers.ReadFollowersTweets({0x1673cd0, 0xc000588700}, 0xc000684300)
  20. /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/routers/readFollowersTweets.go:24 +0x10a
  21. net/http.HandlerFunc.ServeHTTP(...)
  22. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046
  23. github.com/JeffersonGarcia15/Twitter-Clone/middlew.ValidJWT.func1({0x1673cd0, 0xc000588700}, 0xc000684300)
  24. /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/middlew/validJWT.go:20 +0xb2
  25. net/http.HandlerFunc.ServeHTTP(...)
  26. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046
  27. github.com/JeffersonGarcia15/Twitter-Clone/middlew.CheckDB.func1({0x1673cd0, 0xc000588700}, 0xc00059a600)
  28. /Users/jeffersonlopezgarcia/go/src/github.com/JeffersonGarcia15/Twitter-Clone/middlew/checkDB.go:18 +0xa9
  29. net/http.HandlerFunc.ServeHTTP(0xc000684200, {0x1673cd0, 0xc000588700}, 0xc0000a2701)
  30. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046 +0x2f
  31. github.com/gorilla/mux.(*Router).ServeHTTP(0xc0004ba240, {0x1673cd0, 0xc000588700}, 0xc000684100)
  32. /Users/jeffersonlopezgarcia/go/pkg/mod/github.com/gorilla/mux@v1.8.0/mux.go:210 +0x1cf
  33. github.com/rs/cors.(*Cors).Handler.func1({0x1673cd0, 0xc000588700}, 0xc000684100)
  34. /Users/jeffersonlopezgarcia/go/pkg/mod/github.com/rs/cors@v1.8.0/cors.go:219 +0x1bd
  35. net/http.HandlerFunc.ServeHTTP(0xc000559819, {0x1673cd0, 0xc000588700}, 0x106236e)
  36. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2046 +0x2f
  37. net/http.serverHandler.ServeHTTP({0xc00059a450}, {0x1673cd0, 0xc000588700}, 0xc000684100)
  38. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:2878 +0x43b
  39. net/http.(*conn).serve(0xc00031d4a0, {0x16755e0, 0xc00059a2d0})
  40. /usr/local/Cellar/go/1.17/libexec/src/net/http/server.go:1929 +0xb08
  41. created by net/http.(*Server).Serve
  42. /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:

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

That appears to be, from the quoted code:

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

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

  1. 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:

确定