在Golang中共享全局定义的数据库连接与多个包 [英] Sharing a globally defined db conn with multiple packages in Golang

查看:1698
本文介绍了在Golang中共享全局定义的数据库连接与多个包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些关于如何处理db连接的StackOverflow答案。由于它是一个池,我们可以在全局范围内定义它并在多个goroutine中使用它,这是安全的。



我遇到的问题是我将REST API分成多个包。每个包都需要db连接,所以我在启动时打开数据库连接。但即使我在全球范围内定义连接,它只是在包级别。我可以做些什么来潜在地分享多个包?



对于某些情况,我在我的应用程序中使用了PostgreSQL驱动程序和杜松子酒。 方案

还可以选择创建另一个包来保存数据库连接相关设置。然后,它可以具有全局包级别,可以在 main 中进行初始化,并用于导入它的任何包中。

通过这种方式,您可以明确地看到正在导入数据库包。这是一些示例代码。

 包数据库

var(
// DBCon是连接句柄
//为数据库
DBCon * sql.DB






  package main 

导入myApp / database

func main(){

var err错误
database.DBCon,err = sql.Open(postgres,user = myname dbname = dbname sslmode = disable)







  







$ database $ db $

...
}


I've read a few StackOverflow answers on how we handling the db connection. Since it's a pool, we can define it globally and use it in multiple goroutines and it's safe.

The issue I'm having is that I have split my REST API into multiple packages. Each of these packages require a db connection, so I open a database connection in the startup. But even if I define the connection globally, it's only at the package level. What can I do to potentially share it among multiple packages?

For some context I'm using the PostgreSQL driver and gin-gonic in my application.

解决方案

There is also the option of creating another package to hold your database connection related settings. It can then have a package level global, which can be initialized in main and used in any package that is importing it.

This way, you can explicitly see that the database package is being imported. Here is some sample code.

package database

var (
    // DBCon is the connection handle
    // for the database
    DBCon *sql.DB
)


package main

import "myApp/database"

func main() {

    var err error
    database.DBCon, err = sql.Open("postgres", "user=myname dbname=dbname sslmode=disable")

}


package user

import "myApp/database"

func Index() {
    // database handle is available here
    database.DBCon

    ...
}

这篇关于在Golang中共享全局定义的数据库连接与多个包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆