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"`
}
// 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,
})
}
func main() {
engine := gin.Default()
engine.NoRoute(NotFound)
engine.POST("/hello", HelloView)
// 指定端口启动 Gin Web 服务
if err := engine.Run(":8081"); err != nil {
log.Fatalf("Gin Web 启动失败: %s\n", err)
}
}