2、根据标签/分类获取所有文章
ru.GET("/:slug", views.Html.Index)
//http://localhost:8008/c/1 后面这个1是分类的id我们当成参数就行
ru.GET("/c/:id", views.Html.Category)
前端输入的url中携带参数,首先使用gin的context获取请求的上下文环境,进行前端参数的绑定,
func (*HTMLApi) Category(c *gin.Context) {
cidStr := c.Param("id")
cid, err := strconv.Atoi(cidStr)
if err != nil {
log.Println("获取传输的id出错")
c.HTML(200, "category.html", errors.New("分类id查询错误"))
return
}
//获取表单
pageStr := c.Param("page")
page := 1
if pageStr != "" {
page, _ = strconv.Atoi(pageStr)
}
//每页显示的数量
pageSize := 10
//去数据库获取需要的数据
categoryResponse, err := service.GetpostByCategoryId(cid, page, pageSize)
if err != nil {
c.HTML(http.StatusOK, "category.html", err)
return
}
c.HTML(http.StatusOK, "category.html", categoryResponse)
}
service.GetpostByCategoryId(cid, page, pageSize)
函数用返回响应,
func GetpostByCategoryId(cid, page, pageSize int) (*models.CategoryResponse, error) {
categorys, err := dao.GetAllCategory()
if err != nil {
log.Println(err)
return nil, err
}
var postMores []models.PostMore
posts, err := dao.GetPostPageByCategory(cid, page, pageSize)
for _, post := range posts {
categoryName, err :=