我有以下代码:
package main
func main() {
// create a pointer referece of session of Mongo DB
session := mongoDB.CreateSession()
// Question 1 : How to store a pointer reference in a global scope and using anywhere of the code
defer session.Close()
// Note I suppose that the code call to handler methods that call to the Process in the package controller(the last one code)
}
创建MongoDB会话的代码
package mongoDB
func CreateSession() *mgo.Session {
session, err := mgo.Dial("192.168.0.108:27017/databasename")
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
return session
}
我想使用存储在主
中的指针引用的位置package controller
func Process() {
// Question 2 : How can a get the pointer reference store in Question 1 if is posible
collection := mongoDB.CreateCollection(session, "namedatabase", "colectionData")
mongoDB.InsertData(collection, "Ale", "45646565")
}
我们的想法是避免在为所有项目创建的每个函数中通过引用 session (我在主函数中的指针引用)传递。
答案 0 :(得分:0)
您无法拥有controller
个包导入main
。这不是一个好主意(我很确定它甚至不可能)。但这并不意味着您无法在session
中拥有全局controller
变量。
你可以试试这个:
package main
import (
"controller"
"mongoDB"
)
func main() {
// create a pointer referece of session of Mongo DB
session := mongoDB.CreateSession()
defer session.Close()
controller.SetDBSession(session) // Or controller.Init or whatever you like
controller.Process()
}
然后在controller
包裹中:
package controller
import "mongoDB"
// Global session var for the package
var session mongoDB.Session
// SetDBSession sets the mongoDB session to be used by the controller package.
// This function must be called before calling Process()
func SetDBSession(s mongoDB.Session) {
session = s
}
func Process() {
collection := mongoDB.CreateCollection(session, "namedatabase", "colectionData")
mongoDB.InsertData(collection, "Ale", "45646565")
}
使用此解决方案,您只需将会话传递给控制器包一次,让主要负责会话的创建和关闭。