An API boilerplate written in Golang with Gin Framework
- Motivation
- Configuration Manage
- Server Configuration
- Database Configuration
- Develop Application in Docker Compose with Live Reload
- Local Setup Instruction
- Routes
- Logging
- Middlewares
- Boilerplate structure
- Use Packages
- Code Examples
- Lets Build a Endpoint
- Useful Commands
- Container Development Build
- Container Production Build and Up
Write restful API with fast development and developer friendly
- Manage from config.yml file
- Use Gin Web Framework
- Server
environment
is Gin debug logger, useprod
in production anddev
in development mode
server:
host: "0.0.0.0"
port: "8000"
secret: "secret"
environment: "dev" #debug logger ,use `prod` in production
request:
timeout: 100
- Use GORM as an ORM. you just need to configure config.yml file according to your setup.
- Use database
host
aslocalhost
for local development, if docker usepostgres_db
- Database
log_mode
is SQL logger,false
in production andtrue
in development mode
database:
driver: "postgres"
dbname: "test_pg_go"
username: "mamun"
password: "123"
host: "postgres_db" # use "localhost" for local development, `postgres_db` for docker
port: "5432"
log_mode: true # SQL logger , false in production
Follow these steps:
- Make sure install the latest version of docker and docker-compose
- Docker Installation for your desire OS https://docs.docker.com/engine/install/ubuntu/
- Docker Composer Installation https://docs.docker.com/compose/install/
- Run
make dev
Follow these steps:
- Configuration manage from config.yml file
- To add all dependencies for a package in your module
go get .
in the current directory - Locally run
go run main.go
orgo build main.go
and run./main
- The application available and check health on 0.0.0.0:8000/health
- Use logrus - Structured, pluggable logging for Go.
INFO 2022-03-12T00:33:32+03:00 Server is starting at 127.0.0.1:8000
- Use Gin CORSMiddleware
router := gin.New()
router.Use(gin.Logger())
router.Use(gin.Recovery())
router.Use(middleware.CORSMiddleware())
├── config.yml ├── controllers │ ├── controller.go │ └── example_controller.go ├── docker-compose-dev.yml ├── docker-compose-prod.yml ├── Dockerfile ├── Dockerfile-dev ├── go.mod ├── go.sum ├── LICENSE ├── main.go ├── Makefile ├── models │ └── example_model.go ├── pkg │ ├── config │ │ ├── config.go │ │ ├── db.go │ │ └── server.go │ ├── database │ │ ├── database.go │ │ └── migration.go │ ├── helpers │ │ ├── pagination │ │ │ └── pagination.go │ │ ├── response.go │ │ └── search.go │ ├── logger │ │ └── logger.go │ └── routers │ ├── example.go │ ├── index.go │ ├── middleware │ │ └── cors.go │ └── router.go ├── README.md
- Viper - Go configuration with fangs.
- Gorm - The fantastic ORM library for Golang
- Logger - Structured, pluggable logging for Go.
- Air - Live reload for Go apps (Docker Development)
- Example contains sample code of different type of example
- models folder add a new file name
example_model.go
package models
import (
"time"
)
type Example struct {
Id int `json:"id"`
Data string `json:"data" binding:"required"`
CreatedAt *time.Time `json:"created_at,string,omitempty"`
UpdatedAt *time.Time `json:"updated_at_at,string,omitempty"`
}
// TableName is Database Table Name of this model
func (e *Example) TableName() string {
return "examples"
}
- Add Model to migration
package database
import (
"gin-boilerplate/models"
)
//Add list of model add for migrations
var migrationModels = []interface{}{&models.Example{}}
- controller folder add a file
example_controller.go
- Create API Endpoint
- Use any syntax of GORM after
base.DB
, this is wrapper of*gorm.DB
package controllers
import (
"gin-boilerplate/models"
"gin-boilerplate/pkg/logger"
"github.com/gin-gonic/gin"
"net/http"
)
func (base *Controller) CreateExample(ctx *gin.Context) {
example := new(models.Example)
err := ctx.ShouldBindJSON(&example)
if err != nil {
logger.Errorf("error: %v", err)
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err = base.DB.Create(&example).Error
if err != nil {
logger.Errorf("error: %v", err)
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, &example)
}
- routers folder add a file
example.go
package routers
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"gin-boilerplate/controllers"
)
func TestRoutes(route *gin.Engine, db *gorm.DB) {
ctrl := controllers.Controller{DB: db}
v1 := route.Group("/v1")
v1.POST("/example/", ctrl.CreateExample)
}
- Finally, register routes to index.go
package routers
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"net/http"
)
//RegisterRoutes add all routing list here automatically get main router
func RegisterRoutes(route *gin.Engine, db *gorm.DB) {
//Add All route
TestRoutes(route, db)
}
- Congratulation, your endpoint created
0.0.0.0:8000/v1/example/
make dev
: make dev for development workmake build
: make build containermake production
: docker production build and upclean
: clean for all clear docker images
- Run
make build
- Run
make production