tak
(Stefano Pernat)
July 29, 2019, 7:47am
1
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
Thanks
kync
(Ali Koyuncu)
July 29, 2019, 8:49am
2
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
tak
(Stefano Pernat)
July 30, 2019, 6:48am
3
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
}
system
(system)
Closed
October 28, 2019, 6:48am
4
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.