DEV Community

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

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!