Let's say I want to write an application, and have decided to decompose the functionality into individual packages for maintainability. These packages aren't going to be re-used by any other application -- they're all parts of a whole functioning system.
I want all these packages to use the same database. Looking at the database itself you'd see all the table names in one database, not necessarily realizing that they are owned by different packages which do not communicate with each other directly.
1. Do I share credentials to each package and let each make its own connection, or do I create a connection in package main and share that?
2. Regardless of the answer to #1, what is the best way to share? So far I think the best solution is to create some kind of RegisterDB function in each package, and have main's init() get the database info then call it for each package. An alternative I've thought of is to make a package that knows where to get the config file for the app, read it, and return either the connection info or an actual database connection. Then all of the packages would import that package and call it in their init() methods.
This seems like a need that must come up a lot in practice, but I wasn't able to find anything addressing this with a Google search and a search of this list's history, although it could be that the terms "share database connection multiple packages golang" aren't the right ones to use -- it mostly brings up results about connection pools and database driver packages.
Thanks for reading.