In this post, I will show you how to code in Go & mongoDB a small API using a couple of Go tool-kits: Goji and mgo. As usual, find the code at Github: https://github.com/immontilla/mgo-n-goji.git.
Before to start, in case you have never give Go a try, I suggest you to check https://tour.golang.org/ first, and back here afterwards. If you want to learn more about mongoDB before to continue as well, you have a great set of free courses at MongoDB University, pick some from its catalogue and return here later.
Welcome back from your learning tour...
API Specification
Our phone book API will meet these requirements:
- A contact should have a unique nick.
- The nick has to be alphanumeric with a length greater or equal than 3 and lower or equal than 36.
- A contact should have at least one mobile number associated.
- A contact could have one or more email addresses associated.
Pre-requisites
-
Go
You can find the official installation instructions here. I have installed: https://dl.google.com/go/go1.10.3.linux-amd64.tar.gz on my Linux Mint machine.
Ubuntu users have an installation wiki at https://github.com/golang/go/wiki/Ubuntu. -
mongoDB
If you want to install it on your machine, follow this guide: https://docs.mongodb.com/manual/administration/install-community/.
If you are an Ubuntu user you have this specific guide https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/.
You could create an Atlas Free Tier Cluster following https://docs.mongodb.com/manual/tutorial/atlas-free-tier-setup/.
Last but no least, you could use this Vagrant file: https://s3.amazonaws.com/edu-downloads.10gen.com/M040_2018_August/static/handouts/m040/environment_setup.zip. This file belongs to the "M040: New Features and Tools in MongoDB 4.0" course and contains a ready-to-use MongoDB 4.0 instance.
Go tool-kits
- Goji: a HTTP request multiplexer which compares the incoming requests to a list of registered Patterns dispatching to the Handler that corresponds to the first matching Pattern.
- mgo: a MongoDB driver for the Go language. I am using this fork: github.com/globalsign/mgo because the original project is unmaintained.
Installation
To clone:
cd $GOPATH/src && git clone https://github.com/immontilla/mgo-n-goji.git
To install:
cd $GOPATH && go install mgo-n-goji/cmd/app/
To test:
cd $GOPATH/src/mgo-n-goji/tests/postman/ && npm install && npm run test-n-report
To see the test results open your browser at http://localhost:4444/
Pending
- Swagger documentation
- Testing - BDD