Are there any downsides if we use a global variable to handle database operations instead of passing it as an argument to functions and methods or storing it as a field in structs?
What are these downsides (if there are)?
Let's say we create a package inside a project called database, inside that package define a variable called DB var DB *mgo.Database
, and then in project's main function fill it with our mongo database:
func main() {
session, err := mgo.Dial("localhost")
if err != nil {
fmt.Println(err)
return
}
database.DB = session.DB("mydatabase")
// project code
defer session.Close()
}
After that, we use database.DB to interact with our database.
Note that there will be lots of goroutines using database.DB (if it makes any difference)
The question is not opinion based, please take more time to read and understand