我在使用 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{}
// 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 路线
router.HandleFunc("/event/view/{ eventId }/", handlers.ViewEventHandler)
View (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 并显示事件的特定页面。
我的猜测是可能是数据类型解析有问题,但还是尝试了几种方法都失败了。
最佳答案
尝试从您的路由器中删除空格作为 "eventId"!= "eventId "
router.HandleFunc("/event/view/{eventId}/", handlers.ViewEventHandler)
关于mongodb - 使用 golang 转到 MongoDB 中的特定文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35107134/