英文:
How to maintain MongoDB session throughout out application in goLang as global variable
问题
我是一个GoLang的初学者。我想在整个应用程序中保持一个MongoDB会话。我已经看到了一些答案,比如在martini框架中绑定DB会话或将其分配给GoLang结构体。但我想要一个简单直接的方法。
英文:
I am a beginner in GoLang. I want to maintain a MongoDB session throughout the application. I already have seen answers like binding DB session in martini framework or assigning it to a goLang structs. But I want a straight forward method.
答案1
得分: 2
我假设你已经安装了mgo
驱动程序:
go get gopkg.in/mgo.v2
在你的代码中,你可以在main
函数之外设置一个全局变量,如下所示:
var mgoSession *mgo.Session
然后,在init
函数或者main
函数中启动你的会话:
session, err := mgo.Dial("mongodb://localhost")
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
mgoSession = session
然后,你可以根据需要在程序的不同函数中克隆会话:
session := mgoSession.Clone()
defer session.Close()
c := session.DB("databasename").C("collectionname")
英文:
I'm assuming you've already got the mgo
driver:
go get gopkg.in/mgo.v2
In your code you can set a global variable outside your main
function like:
var mgoSession *mgo.Session
Then either in an init
function or right in your main
function you start up your session:
session, err := mgo.Dial("mongodb://localhost")
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
mgoSession = session
Then you can clone the session as needed in the different functions in your program:
session := mgoSession.Clone()
defer session.Close()
c := session.DB("databasename").C("collectionname")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论