Files
web_template/internal/handler/game.go
2026-07-10 10:06:38 +00:00

104 lines
2.4 KiB
Go

package handler
import (
"strconv"
"gotest/internal/service"
"github.com/gin-gonic/gin"
)
// GameHandler 游戏数据处理器
type GameHandler struct {
svc *service.GameService
}
// NewGameHandler 创建游戏数据处理器
func NewGameHandler(svc *service.GameService) *GameHandler {
return &GameHandler{svc: svc}
}
// GetHomeData 获取游戏首页数据 GET /api/v1/game/home
func (h *GameHandler) GetHomeData(c *gin.Context) {
data, err := h.svc.GetHomeData()
if err != nil {
FailInternal(c, "获取首页数据失败")
return
}
Success(c, data)
}
// ListCategories 获取游戏分类 GET /api/v1/game/categories
func (h *GameHandler) ListCategories(c *gin.Context) {
data, err := h.svc.ListCategories()
if err != nil {
FailInternal(c, "获取分类失败")
return
}
Success(c, data)
}
// ListGames 获取游戏列表 GET /api/v1/game/games?category_id=&keyword=&sort=&page=&page_size=
func (h *GameHandler) ListGames(c *gin.Context) {
categoryID, _ := strconv.ParseUint(c.Query("category_id"), 10, 64)
keyword := c.Query("keyword")
sort := c.Query("sort")
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "12"))
if page < 1 {
page = 1
}
if pageSize < 1 || pageSize > 100 {
pageSize = 12
}
data, err := h.svc.ListGames(uint(categoryID), keyword, sort, page, pageSize)
if err != nil {
FailInternal(c, "获取游戏列表失败")
return
}
Success(c, data)
}
// GetGame 获取游戏详情 GET /api/v1/game/games/:id
func (h *GameHandler) GetGame(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
FailBadRequest(c, "无效的游戏 ID")
return
}
data, err := h.svc.GetGame(uint(id))
if err != nil {
FailBadRequest(c, "游戏不存在")
return
}
Success(c, data)
}
// ListHot 获取热门游戏 GET /api/v1/game/hot?limit=
func (h *GameHandler) ListHot(c *gin.Context) {
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "8"))
if limit < 1 || limit > 50 {
limit = 8
}
data, err := h.svc.ListHot(limit)
if err != nil {
FailInternal(c, "获取热门游戏失败")
return
}
Success(c, data)
}
// ListNew 获取新游 GET /api/v1/game/new?limit=
func (h *GameHandler) ListNew(c *gin.Context) {
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "4"))
if limit < 1 || limit > 50 {
limit = 4
}
data, err := h.svc.ListNew(limit)
if err != nil {
FailInternal(c, "获取新游失败")
return
}
Success(c, data)
}