文章目錄
1. 搜尋商品
1.1 路由接口注冊
1.2 接口函數編寫
1.2.1 service層
1.2.2 api層
1.3 服務函數編寫
1.4 驗證服務
v1.POST("products", api.SearchProducts)
定義一個搜尋商品的服務結構體
結構體中的info就是傳送過來的要搜尋商品的資訊
type SearchProductsService struct {
Info string `form:"info" json:"info"`
PageNum int `form:"pageNum"`
PageSize int `form:"pageSize"`
}
定義這個結構體的搜尋方法
func (service *SearchProductsService) Search() serializer.Response {
...
}
定義搜尋商品服務的對象
searchProductsService := service.SearchProductsService{}
綁定這個結構對象到上下文中
c.ShouldBind(&searchProductsService)
調用商品服務對象下的搜尋方法
res := searchProductsService.Search()
上下文傳回
c.JSON(200, res)
完整代碼
func SearchProducts(c *gin.Context) {
searchProductsService := service.SearchProductsService{}
if err := c.ShouldBind(&searchProductsService); err == nil {
res := searchProductsService.Search()
c.JSON(200, res)
} else {
c.JSON(200, ErrorResponse(err))
logging.Info(err)
}
}
定義商品模型對象清單
var products []model.Product
code := e.SUCCESS
如果傳送過來的是頁數是0的話,就預設是15
if service.PageSize==0 {
service.PageSize=15
}
LIKE對資料庫進行模型搜尋
err := model.DB.Where("name LIKE ?", "%"+service.Info+"%").
Offset((service.PageNum - 1) * service.PageSize).
Limit(service.PageSize).Find(&products).Error
傳回資料
return serializer.Response{
Status: code,
Data: serializer.BuildProducts(products),
Msg: e.GetMsg(code),
}
商品請求

響應傳回