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
", err)
}
}