I usually declare a public Db
variable in the main package
package main
var Db *sql.DB
func main() {
var err error
Db, err = sql.Open("sqlite3", BARS_FILE)
if err != nil {
log.Fatal(err)
}
defer Db.Close()
// passing Db as a parameter to other functions in other packages (database
// repositories)
}
Is there a better way of doing this?
According to http://golang.org/pkg/database/sql/#DB it is safe to use sql.DB this way:
DB is a database handle. It's safe for concurrent use by multiple goroutines.
And IMHO it is ok to use it that way. Maybe later, when this variable becomes bottleneck you could create more handles. It could happen if a lot of gouroutines start using it. But do not optimize before it is necessary.