英文:
Errors Getting list of polls from mongoDB with go-gin and mgo
问题
你好,以下是翻译好的内容:
嗨,我正在尝试使用Go语言的go-gin和mgo构建一个Web服务,我有一个带有MongoDB的数据库,但每次我尝试从数据库中获取投票时,我都会从Go Web服务器中获得以下错误。
我的代码如下:
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\n", 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,
})
}
我的数据库如下:
{
"_id" : ObjectId("58d9cf1cdf353f3d2f5951b4"),
"id" : "1",
"firstname" : "Sam",
"lastname" : "Smith",
"poll" : "Who is the Richest Man in the World"
}
希望对你有帮助!
英文:
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\n", 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"
}
答案1
得分: 1
要从gin上下文(c)中获取数据库对象(db) c.MustGet("db").(*mgo.Database)
,你首先需要使用gin中间件函数进行设置。
func ConnectMiddleware(c *gin.Context) {
c.Set("db", Session.DB(Mongo.Database))
c.Next()
}
然后通过以下代码使用这个中间件:
router := gin.Default()
router.Use(ConnectMiddleware)
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "OK"})
})
router.GET("/polls", allPolls)
你正在使用一个过时的gin库版本,其他部分的代码都没问题。
导入最新的github.com/gin-gonic/gin
包。
使用以下代码从数据库获取数据:
func allPolls(c *gin.Context) {
db := c.MustGet("db").(*mgo.Database)
polls := []Poll{}
err := db.C(CollectionPoll).Find(nil).All(&polls)
if err != nil {
c.Error(err)
}
result := gin.H{"payload": polls}
c.Writer.Header().Set("Content-Type", "application/json")
c.JSON(200, result)
}
英文:
To get the database object (db) from the gin context (c) c.MustGet("db").(*mgo.Database)
you have to first set it using a gin middleware function
func ConnectMiddleware(c *gin.Context) {
c.Set("db", Session.DB(Mongo.Database))
c.Next()
}
and then use this middleware through the following code
router := gin.Default()
router.Use(ConnectMiddleware)
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "OK"})
})
router.GET("/polls", allPolls)
You are using a outdated version of gin library other things are fine in your code
import the latest package form github.com/gin-gonic/gin
Use this to get the data from the database
func allPolls(c *gin.Context) {
db := c.MustGet("db").(*mgo.Database)
polls := []Poll{}
err := db.C(CollectionPoll).Find(nil).All(&polls)
if err != nil {
c.Error(err)
}
result := gin.H{"payload": polls}
c.Writer.Header().Set("Content-Type", "application/json")
c.JSON(200, result)
}
答案2
得分: 0
在你的请求中没有名为"db"的变量。
当你执行c.MustGet("db")
时,你确保有一个名为"db"的参数,但实际上并没有提供。
你需要在请求中传递"name"参数。
更好的解决方案是:如果参数不存在,则返回HTTP错误400 Bad Request。
英文:
There is no variable named "db" in your request.
When you're executing c.MustGet("db")
you're assure that there is a param with this name, but it isn't presented.
You need to pass "db" name in to your request.
Better solution: if it's not present return HTTP error 400 Bad request.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论