英文:
Go to a particular document in MongoDB using golang
问题
我在使用gorilla和mgo时遇到了一个问题,无法访问特定的文档(在这种情况下是一个事件)。
事件模型:
Id bson.ObjectId `bson:"_id,omitempty"`
Email string `bson:"user_email"`
Name string `bson:"name"`
Category string `bson:"category"`
Description string `bson:"description"`
Status string `bson:"status"`
事件处理程序:
func ViewEventHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
eventId := vars["eventId"]
session, err := mgo.Dial("mongodb://DATABASE_URL")
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("DATABASE_NAME").C("event")
result := model.EventModel{}
// 下面这行代码可能有问题
err = c.FindId(bson.ObjectIdHex(eventId)).One(&result)
if r.Method == "GET" {
t, _ := template.ParseFiles("templates/view/event.html");
t.Execute(w, result);
}
}
在主函数中的Gorilla路由:
router.HandleFunc("/event/view/{eventId}/", handlers.ViewEventHandler)
视图(html):
<td><a href="/event/view/{{ .Id.Hex }}/">{{ .Name }}</a></td>
错误信息:
2016/01/30 22:06:01 http: panic serving 127.0.0.1:41254: Invalid input to ObjectIdHex: ""
我想要的是访问路由/event/view/Id,并显示特定事件的页面。
我猜测可能是数据类型解析的问题,但是尝试了几种方法都失败了。
英文:
I am having a problem to go to a particular document (in this case an event) using gorilla and mgo.
The event model :
Id bson.ObjectId `bson:"_id,omitempty"`
Email string `bson:"user_email"`
Name string `bson:"name"`
Category string `bson:"category"`
Description string `bson:"description"`
Status string `bson:"status"`
The event handler
func ViewEventHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
eventId := vars["eventId"]
session, err := mgo.Dial("mongodb://DATABASE_URL")
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("DATABASE_NAME").C("event")
result := model.EventModel{}
// the following line is probably the problem
err = c.FindId(bson.ObjectIdHex(eventId)).One(&result)
if r.Method == "GET" {
t, _ := template.ParseFiles("templates/view/event.html");
t.Execute(w, result);
}
}
Gorilla route in main
router.HandleFunc("/event/view/{ eventId }/", handlers.ViewEventHandler)
The View (html)
<td><a href="/event/view/{{ .Id.Hex }}/">{{ .Name }}</a></td>
The Error
2016/01/30 22:06:01 http: panic serving 127.0.0.1:41254: Invalid input to ObjectIdHex: ""
What I want is to go to the route /event/view/Id and show the particular page of the event.
My guess is that there is probably a data type parsing problem, but still tried a few ways and failed.
答案1
得分: 1
尝试将路由器中的空格移除,将"eventId"更改为"eventId"。
router.HandleFunc("/event/view/{eventId}/", handlers.ViewEventHandler)
英文:
Try to remove spaces from your router as "eventId" != " eventId "
router.HandleFunc("/event/view/{eventId}/", handlers.ViewEventHandler)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论