Golang Gin template
🚀 This is a template for web apps using Golang, Gin, Docker and Kubernetes!
Contents
Architecture
This is an REST API, made with Golang and Gin. You can manually run it or use docker-compose (recommended) or Kubernetes to get everthing up.
Directory Structure
The project is divided by the following strucure:
.github
|__ workflows
k8s
routes
services
|__ db
These following directory has some misc files, not directly related to the API code:
-
.github/ holds the GitHub templates.
-
.github/worflows has the CI pipelines for GitHub Actions.
-
k8s Kubernetes services and pods config files.
For the API, this is the direcoty rules:
-
routes has the Gin definitions of the endpoints routes.
-
services holds the services used across the code like the database.
-
services/db holds the databases integrations (MySQL and Redis).
Building
By far, the easiest way to get everything running is with docker-compose
. See the docker-compose section. First, set up the environment variables for your project. You can user the .env.example
:
$ source .env.example
Binary
To build the binary, run the following:
$ go build -o ${APP_NAME}
To run the binary, run the following:
$ ./${APP_NAME}
Or simply:
$ go run main.go
Makefile
To run the through the Makefile, run the following
$ source .env
$ make run
Docker
Make sure you have Docker installed on your machine.
To build the Docker image, run the following:
$ docker build . -t ${APP_NAME}
To run the Docker image, run:
$ docker run -p $PORT:$PORT ${APP_NAME}
docker-compose
To run the docker-compose:
$ docker-compose up
Kubernetes
To create the Kubernetes pods, make sure you have MinuKube or Kind installed. In this example, we'll be using kind
.
Then run the following command:
Create a cluster:
$ kind create cluster --name=${APP_NAME}
Select the cluster you just created:
$ kubectl cluster-info --context kind-${APP_NAME}
Create the application pods:
$ kubectl apply -f k8s/
Verify pods status:
$ kubectl get pods
Wait until all the pods STATUS are running
.
You can expose the API service port, running:
$ kubectl port-forward service/${APP_NAME} 8080:8080
Testing
The unit testes are written with the default testing tool of Golang.
Unit Tests
To run the unit tests, do the following:
$ go test -v ./...
To run the tests with coverage, do the following:
$ go test -v -covermode=count ./...
Continuous Integration
We use GitHub Actions for our CI tool. Right now we have four workflows, and you can check they state here:
- Building the binary status.
- Unit tests status.
- Building the Docker image status.
- Terraform plan