Add internal/handler/shop.go
This commit is contained in:
89
internal/handler/shop.go
Normal file
89
internal/handler/shop.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"gotest/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ShopHandler 电商数据处理器
|
||||
type ShopHandler struct {
|
||||
svc *service.ShopService
|
||||
}
|
||||
|
||||
// NewShopHandler 创建电商数据处理器
|
||||
func NewShopHandler(svc *service.ShopService) *ShopHandler {
|
||||
return &ShopHandler{svc: svc}
|
||||
}
|
||||
|
||||
// GetHomeData 获取商城首页数据 GET /api/v1/shop/home
|
||||
func (h *ShopHandler) GetHomeData(c *gin.Context) {
|
||||
data, err := h.svc.GetHomeData()
|
||||
if err != nil {
|
||||
FailInternal(c, "获取首页数据失败")
|
||||
return
|
||||
}
|
||||
Success(c, data)
|
||||
}
|
||||
|
||||
// ListCategories 获取分类列表 GET /api/v1/shop/categories
|
||||
func (h *ShopHandler) ListCategories(c *gin.Context) {
|
||||
data, err := h.svc.ListCategories()
|
||||
if err != nil {
|
||||
FailInternal(c, "获取分类失败")
|
||||
return
|
||||
}
|
||||
Success(c, data)
|
||||
}
|
||||
|
||||
// ListProducts 获取商品列表 GET /api/v1/shop/products?category_id=&keyword=&sort=&page=&page_size=
|
||||
func (h *ShopHandler) ListProducts(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.ListProducts(uint(categoryID), keyword, sort, page, pageSize)
|
||||
if err != nil {
|
||||
FailInternal(c, "获取商品列表失败")
|
||||
return
|
||||
}
|
||||
Success(c, data)
|
||||
}
|
||||
|
||||
// GetProduct 获取商品详情 GET /api/v1/shop/products/:id
|
||||
func (h *ShopHandler) GetProduct(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
FailBadRequest(c, "无效的商品 ID")
|
||||
return
|
||||
}
|
||||
data, err := h.svc.GetProduct(uint(id))
|
||||
if err != nil {
|
||||
FailBadRequest(c, "商品不存在")
|
||||
return
|
||||
}
|
||||
Success(c, data)
|
||||
}
|
||||
|
||||
// ListFeatured 获取推荐商品 GET /api/v1/shop/featured?limit=
|
||||
func (h *ShopHandler) ListFeatured(c *gin.Context) {
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "8"))
|
||||
if limit < 1 || limit > 50 {
|
||||
limit = 8
|
||||
}
|
||||
data, err := h.svc.ListFeatured(limit)
|
||||
if err != nil {
|
||||
FailInternal(c, "获取推荐商品失败")
|
||||
return
|
||||
}
|
||||
Success(c, data)
|
||||
}
|
||||
Reference in New Issue
Block a user