Golang“最佳实践”处理与数据库的连接 [英] Golang "Best practice" to handle connection to database
问题描述
我有一个用Go编写的web服务,目前我有这个全局包,我到处导入包含到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
推荐答案
导入导出初始化 * mgo.Session
对象作为包级变量或通过访问器/构造器。也许后者更适合传统的OOP-ists。
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".
这篇关于Golang“最佳实践”处理与数据库的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!