Files

67 lines
1.9 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package routers
import (
"net/http"
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/global"
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/middleware"
v1 "git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/routers/api/v1"
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/wsgateway"
"github.com/gin-gonic/gin"
)
// NewRouter 构建 gin 引擎:注册中间件链与 /api/v1 路由。
func NewRouter() *gin.Engine {
r := gin.New()
// 中间件链:Recovery -> RequestID -> Slog -> CORS
r.Use(
middleware.Recovery(),
middleware.RequestID(),
middleware.GinSlogMiddleware(),
middleware.CORS(),
)
// 健康检查
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "pong"})
})
// WebSocket 建连入口:必须放在鉴权组之外,token 走 query 由 ServeWS 自行校验。
r.GET("/ws", wsgateway.ServeWS)
// handler 实例
userHandler := v1.NewUserHandler()
apiV1 := r.Group("/api/v1")
// ===== 公开路由(无需登录) =====
{
apiV1.POST("/user/wxlogin", userHandler.WxLogin)
apiV1.POST("/user/refresh-token", userHandler.RefreshToken)
}
// ===== 鉴权路由(需登录) =====
auth := apiV1.Group("")
auth.Use(middleware.JWTAuth())
{
auth.GET("/user/info", userHandler.InfoGetBySelf)
auth.PUT("/user/profile", userHandler.ProfileUpdate)
auth.POST("/user/avatar/upload", userHandler.AvatarUpload)
}
// ===== 开发调试路由(仅 debug 模式注册)=====
// 1) /api/v1/dev/token:跳过微信登录直接换取令牌,便于联调
// 2) /test:WebSocket 联调页面(单页面双开两个玩家)
if global.ServerSetting != nil && global.ServerSetting.RunMode == gin.DebugMode {
devHandler := v1.NewDevHandler()
apiV1.GET("/dev/token", devHandler.Token)
r.GET("/test", func(c *gin.Context) {
c.File("web/ws-test.html") // 相对工作目录(项目根)读取静态页面
})
}
return r
}