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) } }