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

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

问题描述

我已经阅读了一些关于如何处理数据库连接的StackOverflow答案.由于它是一个池,因此我们可以全局定义它,并在多个goroutine中使用它,这是安全的.

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.

我遇到的问题是我已将REST API拆分为多个软件包.这些软件包中的每一个都需要一个db连接,因此我在启动时打开了一个数据库连接.但是,即使我在全局范围内定义连接,也只能在程序包级别上进行.我该怎么做才能在多个软件包中共享它?

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?

在某些情况下,我在应用程序中使用PostgreSQL驱动程序和gin-gonic.

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

推荐答案

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

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

    ...
}

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

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