我用一些CRUD方法编写了一个简单的MongoDB软件包:
package backend
import "labix.org/v2/mgo"
type MongoDBConn struct {
session *mgo.Session
}
type ToDo struct {
Title string
Description string
}
func NewMongoDBConn() *MongoDBConn {
return &MongoDBConn{}
}
func (m *MongoDBConn) Connect(url string) *mgo.Session {
session, err := mgo.Dial(url)
if err != nil {
panic(err)
}
m.session = session
return m.session
}
func (m *MongoDBConn) Stop() {
m.session.Close()
}
func (m *MongoDBConn) AddToDo(title, description string) (err error) {
c := m.session.DB("test").C("people")
err = c.Insert(&ToDo{title, description})
if err != nil {
panic(err)
}
return nil
}
我有一个server.go,在其中创建Http Server并具有用于不同URL的处理程序。我希望能够连接到MongoDB并在特定处理程序中调用AddToDo方法。我可以从服务器的主要方法连接到数据库:
import (
"./backend"
//other boilerplate imports
)
func AddHandler(writer http.ResponseWriter, request *http.Request) {
log.Printf("serving %v %v", request.Method, request.URL.Path[1:])
if request.Method != "POST" {
serve404(writer)
return
}
title := request.FormValue("title")
description := request.FormValue("description")
fmt.Fprintf(writer, " title description %v %v", title, description)
//I can't call mongoConn.AddToDo(title, description) from here
}
func main() {
//connect to mongoDB
mongoConn := backend.NewMongoDBConn()
_ = mongoConn.Connect("localhost")
defer mongoConn.Stop()
}
但是我不确定如何从处理程序中调用mongoConn.AddToDo(title,description string)方法。我应该创建一个全局数据库连接变量吗?
倚天杖
慕田峪4524236
相关分类