Creating a Production-Ready Rest API With Go
Creating a ready-made application for microservices in production in 5 minutes
In this article we will make an API Rest with Golang ready to run in production and set to the microservices.
All content shown in this article is available as a Github template at the following link:
Prerequisites:
Before starting, you must have installed Golang in your development environment, so I leave here some links that explain how to install it:
- Windows 10: https://www.digitalocean.com/community/tutorials/how-to-install-go-and-set-up-a-local-programming-environment-on-windows-10-es
- Ubuntu 18.04 LTS: https://www.digitalocean.com/community/tutorials/como-instalar-go-en-ubuntu-18-04-es
- Mac OS: https://www.digitalocean.com/community/tutorials/how-to-install-go-and-set-up-a-local-programming-environment-on-macos-es
Frameworks and Libraries used:
- github.com/swaggo/gin-swagger
- github.com/gin-gonic/gin
- github.com/dgrijalva/jwt-go
- github.com/jinzhu/gorm
- github.com/spf13/viper
How to use this template:
You can create a new project on Github if you access the template repository (https://github.com/antonioalfa22/go-rest-template) using the “Use this template” button:
Using the button will take you to the page to create a new repository, where you can choose whether to include all the branches or not.
The project is formed following the good practices for structuring projects in Golang specified in https://github.com/golang-standards/project-layout
- /cmd: In this folder are the input files to the project (main.go) as well as other files depending on the type of execution (eg database.db, config.yml, etc)
- /docs: In this folder the swagger configuration files are saved to automatically generate the API documentation (available at http://localhost:3000/docs/index.html)
- /internal: The application code is divided into two folders: api and pkg:
- /internal/api: Main application, controllers, middlewares and router
- /internal/pkg: Models, persistence and database.
- /pkg: Modules reusable in other applications (For example: crypto, handlers, etc)
- /test: Project unit tests
- Makefile: It facilitates the use of the application, it has the following format
- Dockerfile: