duanpao9781 2017-06-20 13:10
浏览 119
已采纳

错误使用go-gin和mgo从mongoDB获取民意测验列表

Hi trying to build a web service with go-gin and mgo on the Go language, i have a database with mongoDB but each time i try to GET polls from the database I get errors from the folowing errors from the Go webserver.

    2:00:16 PM web.1 |      gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
    2:00:16 PM web.1 |  /home/go/src/gopkg.in/gin-gonic/gin.v1/context.go:180 (0x4e1eb1)
    2:00:16 PM web.1 |      (*Context).MustGet: panic("Key \"" + key + "\" does not exist")
    2:00:16 PM web.1 |  /home/go/src/smartpoll/main.go:139 (0x401655)
    2:00:16 PM web.1 |      allPolls: db := c.MustGet("db").(*mgo.Database)
    2:00:16 PM web.1 |  /home/go/src/gopkg.in/gin-gonic/gin.v1/context.go:97 (0x4e187a)
    2:00:16 PM web.1 |      (*Context).Next: c.handlers[c.index](c)
    2:00:16 PM web.1 |  /home/go/src/gopkg.in/gin-gonic/gin.v1/recovery.go:45 (0x4f165a)
    2:00:16 PM web.1 |      RecoveryWithWriter.func1: c.Next()
    2:00:16 PM web.1 |  /home/go/src/gopkg.in/gin-gonic/gin.v1/context.go:97 (0x4e187a)
    2:00:16 PM web.1 |      (*Context).Next: c.handlers[c.index](c)
    2:00:16 PM web.1 |  /home/go/src/gopkg.in/gin-gonic/gin.v1/logger.go:72 (0x4f074f)
    2:00:16 PM web.1 |      LoggerWithWriter.func1: c.Next()
    2:00:16 PM web.1 |  /home/go/src/gopkg.in/gin-gonic/gin.v1/context.go:97 (0x4e187a)
    2:00:16 PM web.1 |      (*Context).Next: c.handlers[c.index](c)
    2:00:16 PM web.1 |  /home/go/src/gopkg.in/gin-gonic/gin.v1/gin.go:284 (0x4e7c0e)
    2:00:16 PM web.1 |      (*Engine).handleHTTPRequest: context.Next()
    2:00:16 PM web.1 |  /home/go/src/gopkg.in/gin-gonic/gin.v1/gin.go:265 (0x4e74f0)
    2:00:16 PM web.1 |      (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
    2:00:16 PM web.1 |  /home/kebe/golang/go/src/net/http/server.go:2202 (0x4b249d)
    2:00:16 PM web.1 |      serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
    2:00:16 PM web.1 |  /home/kebe/golang/go/src/net/http/server.go:1579 (0x4aee07)
    2:00:16 PM web.1 |      (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
    2:00:16 PM web.1 |  /home/kebe/golang/go/src/runtime/asm_amd64.s:2086 (0x45a081)
    2:00:16 PM web.1 |      goexit: BYTE    $0x90   // NOP
    2:00:16 PM web.1 |  
    2:00:16 PM web.1 |  [GIN] 2017/06/20 - 14:00:16 | 500 |  753.521212ms | 127.0.0.1 |   GET     /polls

My Code is as follows

package main

import (

    "fmt"
    "log"
    "net/http"  
    "os"

    "gopkg.in/gin-gonic/gin.v1"
    "gopkg.in/mgo.v2"

)

type Poll struct {
    ID        string `json:"id,omitempty"`
    Firstname string `json:"firstname,omitempty"`
    Lastname  string `json:"lastname,omitempty"`
    Poll      string `json:"poll,omitempty"`

}

var (
    // Session stores mongo session
    Session *mgo.Session

    // Mongo stores the mongodb connection string information
    Mongo *mgo.DialInfo
)

const (
    // MongoDBUrl is the default mongodb url that will be used to connect to the
    // database.
    MongoDBUrl = "mongodb://localhost:27017/smartpoll"

        // CollectionPoll holds the name of the articles collection
    CollectionPoll = "polls"
)

// Connect connects to mongodb
func Connect() {
    uri := os.Getenv("MONGODB_URL")

    if len(uri) == 0 {
        uri = MongoDBUrl
    }

    mongo, err := mgo.ParseURL(uri)
    s, err := mgo.Dial(uri)
    if err != nil {
        fmt.Printf("Can't connect to mongo, go error %v
", err)
        panic(err.Error())
    }
    s.SetSafe(&mgo.Safe{})
    fmt.Println("Connected to", uri)
    Session = s
    Mongo = mongo
}


func init() {
    Connect()
}

func main() {
    port := os.Getenv("PORT")

    if port == "" {
        log.Fatal("$PORT must be set")
    }



    router := gin.Default()

    router.GET("/", func (c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "OK"})

    })
    router.GET("/polls", allPolls)
    router.Run(":" + port)
}



func allPolls(c *gin.Context) {
    db := c.MustGet("db").(*mgo.Database)
    polls := []Poll{}
    poll := db.C(CollectionPoll).Find(&polls)

    c.JSON(http.StatusOK, gin.H{

        "_id": "ID",
        "firstname": "Firstname",
        "lastname": "Lastname",
        "poll": poll,
        })
}

My DB is as follows:

/* 0 */
{
    "_id" : ObjectId("58d9cf1cdf353f3d2f5951b4"),
    "id" : "1",
    "firstname" : "Sam",
    "lastname" : "Smith",
    "poll" : "Who is the Richest Man in the World"
}
  • 写回答

2条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 unity 使用 Vuforia 导入Model target 成功后database下拉菜单不显示导入的内容
      • ¥15 VBA跨工作簿获取目标工作簿内已有数据的列号
      • ¥30 Dijkstra‘s 最短路径
      • ¥15 在线教育培训平台,主要以点播视频和在线练习测试为主,除将视频做切片外,有其他哪种方式降低流量?(关键词-带宽速率)
      • ¥20 用c语音或c++实现银行叫号系统
      • ¥15 人工智能 规则正向演绎和推理
      • ¥20 基于STM32F401的电子密码锁设计
      • ¥15 famamacbeth回归中遇到only size-1 arrays can be converted to Python scalars,求解答
      • ¥15 单片机多个自锁按键的编程实践
      • ¥15 用python操作redis存储中文后,再取出的数据变成了乱码怎么办?