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.

main

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屋!