Article directory
1. Search for products
1.1 Routing interface registration
v1.POST("products", api.SearchProducts)
1.2 Writing interface functions
1.2.1 service layer
- Define a service structure that searches for items
The information in the structure is info
the information of the product to be searched.
type SearchProductsService struct {
Info string `form:"info" json:"info"`
PageNum int `form:"pageNum"`
PageSize int `form:"pageSize"`
}
- Defines the search method for this struct
func (service *SearchProductsService) Search() serializer.Response {
...
}
1.2.2 api layers
- Define the object to search for goods and services
searchProductsService := service.SearchProductsService{
}
- bind this struct object to the context
c.ShouldBind(&searchProductsService)
- Call the search method under the commodity service object
res := searchProductsService.Search()
- context return
c.JSON(200, res)
- full code
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)
}
}
1.3 Writing service functions
- Define a list of commodity model objects
var products []model.Product
code := e.SUCCESS
- If the number of pages sent is 0, the default is 15
if service.PageSize==0 {
service.PageSize=15
}
- LIKE model search on database
err := model.DB.Where("name LIKE ?", "%"+service.Info+"%").
Offset((service.PageNum - 1) * service.PageSize).
Limit(service.PageSize).Find(&products).Error
- return data
return serializer.Response{
Status: code,
Data: serializer.BuildProducts(products),
Msg: e.GetMsg(code),
}
1.4 Authentication Service
- commodity request
- response returned