Multiple database connections

I have multiple postgres databases to work with in my app and im using Gin & Gorm frameworks. I made database package with configs for each database, now I need a way to implement that in my main func… Somehow I need to get information about database trough http request (in headers or …), and based on that information chose the database that will app use… Any ideas ?

Thank you

How many different databases? What have you tried and why does/doesn’t it work well? Is this an API or are you rendering html pages?

I have 3 different databases and yes its REST api. For my project setup im using this structure:

example of structure

So how can you see, on line 65 of main func, is db info… I will have in http request name, or id of database that I should use, and I must set the correct database info there …

You should be able to instantiate multiple sql.DB connection pools, one for each database, and then use the appropriate one each time you need to execute some SQL. I’ve used two sql.DB variables pointing at different databases at the same time with no problem.

I’d be inclined to keep a map[string]*sql.DB in the appropriate place and then accept the map key as an API parameter. That way, it’ll be easily extensible to handle any number of databases.

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