Golang Mongo driver and Openshift
I wanted to learn how to create a rest Api with Golang and MongoDb, found a lot of tutorials using the mgo library but as this was unmaintained. I used the Mongo driver instead with gorilla/mux. First set up package and imports.
Setup the routes and Mongo db connection
Setup the model package
Back in the main package define the
GET all users function
GET find user by id function
DELETE user by id is pretty similar
PUT update user by id
POST create user
So the rest api is all setup at this point to connect to my local MongoDb.
Setup the container and deploy to Openshift
First I set up a project in Openshift 3.11, on Minishift
oc new-project golanguser
Login to the Openshift console and deploy Mongodb from the Openshift catalog. Open the project in the console and click on `Browse Catalog`
Click on Mongodb
Follow the creation flow until you get to `Configuration` set the following as some will be auto generated if you don’t
- Database Service Name
- MongoDB Connection Username
- MongoDB Connection Password
- MongoDB Database Name
- MongoDB Admin Password
Once set click the create button
The Results screen will have the connection url. I will be using part of the connection url in the code.
Change the connection url in the main package here
And make sure that your collection is pointing at the correct db
Once these are set we are ready to create the golang container with the following `dockerfile`
Build the image and push it to a remote registry
docker build -t austincunningham/golanguserrestapi:latest .
docker push austincunningham/golanguserrestapi:latest
You can then add the Image to project in the Openshift console `Add to Project/Deploy Image`
Enter the Image Name click the search icon and deploy when the image is found
Once the container is deployed you can test the connection between MongoDb and the rest api as follows
Final step is to add a route click on the rest container and `create route`
Except the defaults your route will appear in the console it can be accessed from any where with the users route
Code lives on github and the container image on dockerhub