简体   繁体   中英

GoLang multi-tenant application database connections

I am new to golang and currently trying to build a multi-tenant application. In my application each tenants have their own database. My requirement is that I need to switch database connection per tenant request, how can this be accomplished in golang . I prefer postgresql for this project.

I can have a map of database connection to tenant, but not sure if this is a good practice.

Your help and suggestion is highly appreciated

I've handled a similar kind of requirement in Rails. Probably you can use the same approach in go-lang also.

I will have one master DB, which will hold just the tenant information. Like tenant name and db_name.

And I've got a rack middleware which will switch DB based on a subdomain(I'm using the subdomain to identify the tenant).

For example, Your master DB can have table tenants and an example record might probably look like this: { id: 1, name: 'XYZ', db_name: 'xyz' }

and when your application receives a request with subdomain xyz , Your middleware should switch to xyz DB.

its a better solutions to create an schema instead of an entire database and on each request change the schema of the request identifying the tenant.other solutions is to create a database and reopen a connection on each request after the tenant recognition on the middleware

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM