The introduction

  • Download and install GIN, and run it as demo
  • Customize the project structure
  • Encapsulate the Config layer and define the configuration file
  • Github code address

1. Extract routes

Create route.go in the routes directory

package routes

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"

	"go-api/config"
)

//init router
func InitRouter(a) *gin.Engine{
    r := initGin()
	loadRoute(r)
	return r;
}

// init Gin
func initGin(a) *gin.Engine{
	// Set gin mode
	gin.SetMode(config.RunMode)
    return gin.Default()
}

// Load the route
func loadRoute(r *gin.Engine){
	testRoute(r)
	apiRoute(r)
}

// Start the server
func Run(a){
	r := InitRouter()
	s := &http.Server{
		Addr:           fmt.Sprintf("%s:%d",config.ServerSetting.HttpAddress,config.ServerSetting.HttpPort),
		Handler:        r,
		ReadTimeout:    config.ServerSetting.ReadTimeout,// Request the supermarket time for the response
		WriteTimeout:   config.ServerSetting.WriteTimeout,// Return the timeout for the response
		//MaxHeaderBytes: 1 << 20,// Default 1MB
	}
	s.ListenAndServe()
}

Copy the code

Create test.go under Routes

package routes

import (
	"github.com/gin-gonic/gin"
)

func testRoute(r *gin.Engine){
	r.GET("/ping".func(c *gin.Context){
		c.JSON(200, gin.H{
			"message": "pong",})})}Copy the code

demo

package main

import (
    "go-api/routes"
)

func main(a) {
    // Start the server
    routes.Run()
}
Copy the code

Visit and see the return

2. Next we prepare the Model layer and write an example of the controller

Key: ORM we use github.com/jinzhu/gormChinese document

Prepare the SQL

CREATE TABLE `test_user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT ' ' COMMENT 'Label name',
  `created_on` int(10) unsigned DEFAULT '0' COMMENT 'Creation time',
  `created_by` varchar(100) DEFAULT ' ' COMMENT 'Founder',
  `modified_on` int(10) unsigned DEFAULT '0' COMMENT 'Modification time',
  `modified_by` varchar(100) DEFAULT ' ' COMMENT 'Modifier',
  `deleted_on` int(10) unsigned DEFAULT '0',
  `state` tinyint(3) unsigned DEFAULT '1' COMMENT 'State 0 is disabled, state 1 is enabled'.PRIMARY KEY (`id`),
  UNIQUE KEY `uiq-name` (`name`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='User Management';

Copy the code

Create mysql.go in app/models

package models

import (
    "log"
    "fmt"
    "time"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    
    "go-api/config"
)

type mysqlConfig struct{
	dbType string
	dbName string
	dbUser string
	dbPassword string
	dbHost string
	dbTablePrefix string
	LogMode bool
	MaxLifetime time.Duration
} 

var (
	db *gorm.DB
	dbConfig = &mysqlConfig{
		dbType:"mysql",
		dbName:config.MysqlSetting.MysqlName,
		dbUser:config.MysqlSetting.MysqlUser,
		dbPassword:config.MysqlSetting.MysqlPassword,
		dbHost:config.MysqlSetting.MysqlHost,
		dbTablePrefix:config.MysqlSetting.MysqlPrefix,
		MaxLifetime:config.MysqlSetting.MaxLifetime,
	}
)

type Model struct {
    ID int `gorm:"primary_key" json:"id"`
    CreatedOn int `json:"created_on"`
    ModifiedOn int `json:"modified_on"`
}

func init(a) {
    var (
        err error
	)
    db, err = gorm.Open(dbConfig.dbType, fmt.Sprintf("%s:%s@tcp(%s)/%s? charset=utf8&parseTime=True&loc=Local", 
        dbConfig.dbUser, 
        dbConfig.dbPassword,
		dbConfig.dbHost,  
        dbConfig.dbName))

		iferr ! =nil {
			log.Println(err)
		}
		
		gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string  {
			return dbConfig.dbTablePrefix + defaultTableName;
		}
		
		db.SingularTable(true)// Disable the plural table name globally
		db.LogMode(dbConfig.LogMode)/ / true print Log
		db.DB().SetMaxIdleConns(10)// Maximum free connection
		db.DB().SetMaxOpenConns(100)// Maximum database link
		db.DB().SetConnMaxLifetime(dbConfig.MaxLifetime)// Maximum database link lifetime
		//
}

func State(a) string{
	return fmt.Sprintf("%+v",db.DB().Stats())
}

func CloseDB(a) {
    defer db.Close()
}

func (model *Model) BeforeCreate(scope *gorm.Scope) error {
    scope.SetColumn("CreatedOn", time.Now().Unix())

    return nil
}

func (model *Model) BeforeUpdate(scope *gorm.Scope) error {
    scope.SetColumn("ModifiedOn", time.Now().Unix())
    return nil
}
Copy the code

A new user. Go

package models

type User struct {
    Model

    Name string `json:"name"`
    CreatedBy string `json:"created_by"`
    ModifiedBy string `json:"modified_by"`
    State int `json:"state"`
}

func GetUsers(pageNum int, pageSize int, maps interface {}) (users []User) {
    db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&users)
    
    return
}

func GetUserTotal(maps interface {}) (count int){
    db.Model(&User{}).Where(maps).Count(&count)

    return
}

func ExistUserByMaps(maps interface{}) bool {
    var user User
    db.Select("id").Where(maps).First(&user)
    if user.ID > 0 {
        return true
    }

    return false
}

func AddUser(Users map[string]interface{}) bool{
    user := User {
        Name : Users["Name"]. (string),
        State : Users["State"]. (int),
        CreatedBy : Users["CreatedBy"]. (string),
    }
    db.Create(&user)
    return! db.NewRecord(user) }func ExistTagByID(id int) bool {
    var user User
    db.Select("id").Where("id = ?", id).First(&user)
    if user.ID > 0 {
        return true
    }

    return false
}

func DeleteUser(maps interface{}) bool {
    db.Where(maps).Delete(&User{})

    return true
}

func EditUser(id int, data interface {}) bool {
    db.Model(&User{}).Where("id = ?", id).Updates(data)

    return true
}
Copy the code

3. Add user.go to app/ Controller

package controller

import (
	"github.com/gin-gonic/gin"
	"go-api/app/models"
)

func GetUsers(c *gin.Context) {
	maps := make(map[string]interface{})
    data := make(map[string]interface{})
	data["total"] = models.GetUserTotal(maps)
	data["list"]  = models.GetUsers(0.10,maps)
	c.JSON(200, gin.H{
		"status":  "200"."message": "Query successful"."data":    data,
	})
}

func GetUser(c *gin.Context){}func AddUser(c *gin.Context){}func EditUser(c *gin.Context){}func DeleteUser(c *gin.Context){}Copy the code

Adding API Routes

package routes

import (
	"go-api/app/controller"

	"github.com/gin-gonic/gin"
)

func apiRoute(r *gin.Engine){
	apiv1 := r.Group("/api/v1")
	{
		// Get the user list
		apiv1.GET("/users", controller.GetUsers)
	}
}
Copy the code

Execute after compilation

go build -o test.exe .
./test.exe
Copy the code

In the next section we will refine the interface and encapsulate the service layer, as well as using the data validation that comes with GIN

series

  • Serialized a Golang environment build
  • Serial II installation Gin
  • Serial three defines the directory structure
  • Serial four builds case API1
  • Serial five builds case API2
  • Serial six access Swagger interface document
  • Serial seven Log components
  • Serial eight gracefully restarts and stops
  • Serial Makefile build
  • Serial Cron timing mission
  • Serial build command line tools
  • Create a dedicated Cache(First Day)
  • Create your own Cache in 3 days (Second Day)
  • Create a dedicated Cache(Third Day)