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条回答 默认 最新
- douluanzhao6689 2016-10-31 05:35关注
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 yourmain
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")
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 乌班图ip地址配置及远程SSH
- ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
- ¥15 PSPICE制作一个加法器
- ¥15 javaweb项目无法正常跳转
- ¥15 VMBox虚拟机无法访问
- ¥15 skd显示找不到头文件
- ¥15 机器视觉中图片中长度与真实长度的关系
- ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
- ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
- ¥15 java 的protected权限 ,问题在注释里