DEV Community

Discussion on: Build an API endpoint with GOlang , Gin & mongoDB

Collapse
 
singhayushh profile image
Ayush Singh

I have a question here.

Looking at the DBInstance and OpenCollection functions, it seems the app is dialing up connection to the database for every api call, or at every instance a collection is being used. So isn't there a roundabout way to have the database connection on as long as the server is running so that you don't have to dial up and end connections to the db for every call.

Collapse
 
iqquee profile image
Mathias Jiya

A connection to the database has to be closed after finished using to avoid leaks. And so, the connection would only open when you need to access that resources again and closes after which you are done accessing that resource.

Collapse
 
joojodontoh profile image
JOOJO DONTOH

Hi Ayush,
Thank you for you question. As far as I know, you can use the "gopkg.in/mgo.v2" package to create connection sessions which can be sent in the context of your router/http handler when API calls are made. However the common occurrence is that most people close (db.cose/ defer cancel) the db session after it has been used to free up resources that may be put back in the pool or collected, depending on the case. This also prevents memory leaks. You are absolutely right about dialing up a connection to the database for every api call. I can change this by creating the database client once the server starts running in the main.go file, and then send the client within context to various routes that need it. This should keep the connection open during server life for I/O actions on collections

Collapse
 
singhayushh profile image
Ayush Singh

Alright, it's a lot clear now.
Thank you for clearing my doubt!