Getting Started with Golang and MongoDB

Noah Kreiger
2 min readDec 29, 2020

In this tutorial we will set-up a local GoLang API development environment for MongoDB with the Mongo Express GUI.

Let’s get started!

We cannot connect to Mongo unless we have an instance of MongoDB actually running. There are multiple ways to accomplish this, but the simplest for local development is to spin up a docker container running mongo.

For this, we will use docker-compose to spin up the instance and the GUI on top of it.

docker-compose -f mongo-compose.yaml up -d

After the services are up you should be able to navigate to http://0.0.0.0:8081/ and see your Mongo Express GUI overlaying.

Mongo Express GUI

Now that we have confirmed our local instance of Mongo and the GUI is running, we can create our API. It will have one simple handler that confirms the connection to the database.

I prefer to serve my API’s gracefully, a great tutorial is located here.

We’ve routed all traffic from ${host}/health to the services.Health handler.

This is a very simple handler that calls the mongo.Connect function and returns the appropriate http status based on the response.

  • *Important to note the client.Disconnect function that ensures we are ALWAYS clearing our MongoDB connections because their is a finite amount of connections allowed to a mongo instance

The last piece of the puzzle is to create the actual mongo client function that will both to connect to mongo and send a ping to verify the connection.

We can now test our API with a simple

go run main.goGET http://localhost:8080/health

If you stop the docker container running Mongo it should return a 400, and if you start it again, you should receive the appropriate 200.

--

--

Noah Kreiger

Software Engineer, DevOps Focus. Always learning and improving.