How can I share a db connection with multiple http handlers?

Hi all,
I’m quite new to golang, I’m building a little web that uses a mysql database to store some data.

What is the best way to share a db connection (mysql) between all handlers and close it properly?

I’d like to avoid to open the connection on every single handler


func withDBContext(fn func(db *sql.DB)) error {
        conn := GetDB()
        // don't call defer conn.Close() here, fn can run concurrently
        return fn(conn)

And then you can use above function like the following :

func foo() {
    withDBContext(func(db *sql.DB) error {
        defer db.Close() // If you have to close the db every time otherwise you don't need to close db here, it is a connection pool it will handle connections for you
        // do something with your code

This is how I do.

1 Like

Thanks for your suggestions, my approach was slightly different
I wrapped my db connection inside a struct like this

type Store struct {
    connection *sql.DB

and used it inside my server struct (where I placed my http handlers)

type Server struct {
    tlp   *template.Template
    store *database.Store

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.