Sharing a globally defined db conn with multiple packages

前端 未结 2 506
感动是毒
感动是毒 2020-12-12 18:30

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.

2条回答
  •  执念已碎
    2020-12-12 18:58

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

提交回复
热议问题