1. 展示商品
1.1 路由接口注冊
GET請求擷取商品清單
v1.GET("products", api.ListProducts)
1.2 接口函數編寫
1.2.1 service層
建立一個展示商品的結構體
type ListProductsService struct {
PageNum int `form:"pageNum"`
PageSize int `form:"pageSize"`
CategoryID uint `form:"category_id" json:"category_id"`
}
建立該結構體下的清單方法
func (service *ListProductsService) List() serializer.Response {
...
}
1.2.2 api層
建立一個展示清單服務對象
listProductsService := service.ListProductsService{}
綁定資料
c.ShouldBind(&listProductsService)
調用展示商品清單對象下的展示方法
res := listProductsService.List()
傳回上下文
c.JSON(200, res)
api層完整代碼
func ListProducts(c *gin.Context) {
listProductsService := service.ListProductsService{}
if err := c.ShouldBind(&listProductsService); err == nil {
res := listProductsService.List()
c.JSON(200, res)
} else {
c.JSON(200, ErrorResponse(err))
logging.Info(err)
}
}
1.3 服務函數編寫
建立一個商品清單模型對象
var products []model.Product
設定分頁
if service.PageSize == 0 {
service.PageSize = 15
}
如果分類傳過來是0的話就傳回所有的商品
if service.CategoryID == 0 {
if err := model.DB.Model(model.Product{}).
Count(&total).Error; err != nil {
logging.Info(err)
code = e.ErrorDatabase
return serializer.Response{
Status: code,
Msg: e.GetMsg(code),
Error: err.Error(),
}
}
if err := model.DB.Offset((service.PageNum - 1) * service.PageSize).
Limit(service.PageSize).Find(&products).
Error; err != nil {
logging.Info(err)
code = e.ErrorDatabase
return serializer.Response{
Status: code,
Msg: e.GetMsg(code),
Error: err.Error(),
}
}
不為0的話,就傳回對應分類的商品
if err := model.DB.Model(model.Product{}).Preload("Category").
Where("category_id = ?", service.CategoryID).
Count(&total).Error; err != nil {
logging.Info(err)
code = e.ErrorDatabase
return serializer.Response{
Status: code,
Msg: e.GetMsg(code),
Error: err.Error(),
}
}
序列化傳回所有的商品,注意要傳回所有商品的總數
for _, item := range products {
products := serializer.BuildProduct(item)
productList = append(productList, products)
}
return serializer.BuildListResponse(serializer.BuildProducts(products), uint(total))
1.4 驗證服務
發送請求

擷取響應