Complete Golang Microservice example
I started to learn about golang some time ago and just thought to share some of the things I learned with the community.
Why Go
- Go has a native concurrency model that is unlike most popular programming languages. Instead of locking variables to share memory, Golang allows you to communicate the value stored in your variable from one thread to another.
- Go belongs comes from C family, but it is much more better than C/C++, I thing Go has barrowed some features from java script but its better than java script as well.
- Go code normally compiles in to a single native binary, which basically makes deploying an application written in Go as easy as copying the application file to the destination server. (that is build on windows and deploy on windows)
What are the available frameworks for Go microservices
Like java has Springboot there is no real go to frameworks in Golang to build microservices but it has many.
Database Schema
Following database schema is using the develop microservice. Idea is to have multiple tables and couple of end points to handle complex scenarios. In this example we will use mysql
Start Developing Microservice
In this tutorial I am using labstack, but you can try the same with different frameworks
Step 1
This is the basic step, writing the main func which can start your first micro service. check the github for the complete example.
Step 2
As this is going to be a complete example we need to start working from the back end, how we connect to database. As familiar design pattern we externalize the database credentials in to a property file
Step 3
This step will tell you how to load properties to you go application
- Create suitable data structures as below
- load the configurations
configFilepath := strings.TrimRight(config, "/") + "/server.config.json"
Step 4
Create database connection and models
- Create database connection, Here I have used ORM framework named GORM. Please check other ORM frameworks for golang https://reposhub.com/go/orm
- Data Model, so there are 3 main data models
Step 5
This will write all the DAO which write and read from the database for user and task tables. Check my github for other implementations
Step 6
This will write api handlers r controllers for you
Sample create user handler is show below
Step 7
Connect handlers to main func is the last step
I have included a POSTMAN collection https://www.getpostman.com/collections/cc9b1cf91bbef21a2871
So you may get chance to test my API
Please find the complete source code here.
If you like this page please Buy me a Coffee — https://www.buymeacoffee.com/shareknowlage