wp-go/route/actions.go

87 lines
2.2 KiB
Go
Raw Normal View History

2022-09-01 02:31:11 +00:00
package route
import (
"github.com/gin-gonic/gin"
2022-09-14 05:28:31 +00:00
"github/fthvgb1/wp-go/models"
2022-09-01 02:31:11 +00:00
"net/http"
2022-09-14 05:28:31 +00:00
"strconv"
"sync"
2022-09-01 02:31:11 +00:00
)
2022-09-14 05:28:31 +00:00
var PostsCache sync.Map
2022-09-01 02:31:11 +00:00
func index(c *gin.Context) {
2022-09-14 05:28:31 +00:00
page := 1
pageSize := 10
p := c.Query("paged")
if pa, err := strconv.Atoi(p); err != nil {
page = pa
}
status := []interface{}{"publish", "private"}
posts, _, err := models.SimplePagination[models.WpPosts](models.SqlBuilder{{
"post_type", "post",
}, {"post_status", "in", ""}}, "ID", page, pageSize, models.SqlBuilder{{"post_date", "desc"}}, nil, status)
if err != nil {
return
}
var all []uint64
var allPosts []models.WpPosts
var needQuery []interface{}
for _, wpPosts := range posts {
all = append(all, wpPosts.Id)
if _, ok := PostsCache.Load(wpPosts.Id); !ok {
needQuery = append(needQuery, wpPosts.Id)
}
}
if len(needQuery) > 0 {
rawPosts, err := models.Find[models.WpPosts](models.SqlBuilder{{
"Id", "in", "",
2022-09-14 13:30:59 +00:00
}}, "a.*,d.name category_name", "", nil, models.SqlBuilder{{
2022-09-14 05:28:31 +00:00
"a", "left join", "wp_term_relationships b", "a.Id=b.object_id",
}, {
"left join", "wp_term_taxonomy c", "b.term_taxonomy_id=c.term_taxonomy_id",
}, {
"left join", "wp_terms d", "c.term_id=d.term_id",
}}, 0, needQuery)
if err != nil {
return
}
for _, post := range rawPosts {
PostsCache.Store(post.Id, post)
}
}
for _, id := range all {
post, _ := PostsCache.Load(id)
pp := post.(models.WpPosts)
allPosts = append(allPosts, pp)
}
2022-09-14 13:30:59 +00:00
recent, _ := recentPosts()
archive, _ := archives()
2022-09-01 02:31:11 +00:00
c.HTML(http.StatusOK, "index.html", gin.H{
2022-09-14 13:30:59 +00:00
"posts": allPosts,
"options": models.Options,
"recentPosts": recent,
"archives": archive,
2022-09-01 02:31:11 +00:00
})
}
2022-09-14 13:30:59 +00:00
func recentPosts() (r []models.WpPosts, err error) {
r, err = models.Find[models.WpPosts](models.SqlBuilder{{
"post_type", "post",
}, {"post_status", "publish"}}, "ID,post_title", "", models.SqlBuilder{{"post_date", "desc"}}, nil, 5)
if err != nil {
return
}
return
}
func archives() (r []models.PostArchive, err error) {
r, err = models.Find[models.PostArchive](models.SqlBuilder{
{"post_type", "post"}, {"post_status", "publish"},
}, "YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts", "year,month", models.SqlBuilder{{"year", "desc"}, {"month", "desc"}}, nil, 0)
return
}