Gin_01_官网Default示例拆分

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

/*
@Author: CarpLi
@Time  : 2020/11/28 8:47 下午
@Desc  : 官方例子拆分
*/

// 创建Gin.Engine
func createEngine() *gin.Engine {
    engine := gin.New()
    registerRoute(engine)
    registerMiddleware(engine)
    return engine
}

// 注册中间件
func registerMiddleware(engine *gin.Engine) {
    engine.Use(gin.Logger())
    engine.Use(gin.Recovery())
}

// 视图函数
func hello(context *gin.Context) {
    context.JSON(http.StatusOK, gin.H{"word": fmt.Sprintf("Hello, Gin!")})
}

// 路由注册
func registerRoute(engine *gin.Engine) {
    engine.GET("/get/hello", hello)
    engine.POST("/post/hello", hello)
    // 路由分组
    api := engine.Group("/api")
    api.GET("/hello", hello)
}

func main() {
    engine := createEngine()
    // 启动Gin服务
    if err := engine.Run("127.0.0.1:8081"); err != nil {
        fmt.Printf("服务启动失败:%v\n", err)
    }
}

你可能感兴趣的:(Gin_01_官网Default示例拆分)