处理与数据库的连接的Golang“最佳实践”

huangapple go评论87阅读模式
英文:

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".

huangapple
  • 本文由 发表于 2014年4月28日 14:13:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/23333753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定