1. 程式人生 > 其它 >Gin_02_單檔案拆解基本模組

Gin_02_單檔案拆解基本模組

package main

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

// ApiResponse 封裝一個響應結構體
type ApiResponse struct {
	Code    uint8  `json:"code"`
	Msg     string `json:"msg"`
	MsgCode uint8  `json:"msg_code"`
	Data    gin.H  `json:"data"`
}

// CreateEngine 建立Gin.Engine
func CreateEngine() *gin.Engine {
	engine := gin.New()
	RegisterMiddleware(engine)
	RegisterRoute(engine)
	return engine
}

// RegisterMiddleware 註冊中介軟體
func RegisterMiddleware(engine *gin.Engine) {
	engine.Use(gin.Logger())
	engine.Use(gin.Recovery())
}

// HelloView 第一個檢視函式
func HelloView(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, ApiResponse{
		Code:    1,
		Msg:     "請求成功",
		MsgCode: 100,
		Data: gin.H{
			"url":      ctx.Request.URL.String(),
			"method":   ctx.Request.Method,
			"datetime": time.Now().Format("2006-01-02 15:04:05"),
			"message":  "Hello, Gin!",
		},
	})
}

// NotFound 404檢視函式
func NotFound(ctx *gin.Context) {
	ctx.JSON(http.StatusNotFound, ApiResponse{
		Code:    0,
		Msg:     "請求失敗",
		MsgCode: 104,
		Data:    nil,
	})
}

// RegisterRoute 路由註冊
func RegisterRoute(engine *gin.Engine) {
	engine.GET("/hello", HelloView)
	engine.POST("/hello", HelloView)
	// 路由組
	ApiV1Group := engine.Group("/v1")
	{
		ApiV1Group.GET("/hello", HelloView)
		ApiV1Group.POST("/hello", HelloView)
	}
	// 404 返回介面資料
	engine.NoRoute(NotFound)
}

func main() {
	engine := CreateEngine()
	// 啟動Gin服務
	if err := engine.Run("127.0.0.1:8081"); err != nil {
		log.Panicf("服務啟動失敗:%v\n", err)
	}
}