How to distribute database connection across all golang file ?

601 views
Skip to first unread message

Shishira Pradhan

unread,
Jan 8, 2022, 9:29:07 AM1/8/22
to golang-nuts
Hello All,

What is the appropriate and industry standard mechanism to send database connection across golang file to use in logic layer to get data from DB? It should be one time connection established and many time use the connection pool across all files.

Thanks,
Shishira

Amit Saha

unread,
Jan 8, 2022, 9:53:00 PM1/8/22
to golang-nuts
The usual pattern is to have a global *sql.Db object obtained via calling the Open() function as explained at [1]. You don't have to worry about maintaining the connection pool yourselves as that's automatically done. The Go tutorial on the topic [2] shows you can do this using a global variable. You can configure various properties of the pool via functions such as SetMaxOpenCons [3] amd SetConnMaxIdleTime[4].

If you are using a struct for managing the other configuration in your application, you would have the *sql.Db object as a field in that struct and then share that struct value with all the parts of your application that needs access to it.

Chris Burkert

unread,
Jan 11, 2022, 3:35:21 PM1/11/22
to Shishira Pradhan, golang-nuts
Hi,
The standard sql package (https://pkg.go.dev/database/sql) comes with a connection pool. I think it is the DB struct handling the pool.
The drivers which implement the details for a specific database product usually come with plenty of documentation and examples. See 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/bd5646b9-0615-4551-bafd-c0a2cd47ba22n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages