英文:
Golang "Best practice" to handle connection to database
问题
我有一个用Go语言编写的Web服务,目前我在每个地方都导入一个名为Global的包,其中包含与MongoDB的连接(通过MGO实现),但我必须说这让我感到非常不舒服。在Go语言中,如何最佳实践地维护与数据源的连接?我来自PHP世界,所以才会有这个Global :S
英文:
I have a webservice written in Go and currently I have this Global package I import everywhere which contains the connection to MongoDB (via MGO), but I have to say that this feels very icky to me. What is the best practice of maintaining connections to datasources in Go? I come from a PHP world, hence the Global :S
答案1
得分: 6
将一个导出了初始化的*mgo.Session
对象的包作为包级变量或通过访问器/初始化器导入是没有问题的。也许后者更适合经典的“面向对象”的支持者。
英文:
There is nothing wrong with importing a package which exports an initialized *mgo.Session
object either as a package-level variable or through an accessor/initializer. Maybe the latter appeals better to classical "OOP-ists".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论