GoBlog/blogstats.go

50 lines
1.3 KiB
Go
Raw Normal View History

2021-01-04 19:29:49 +00:00
package main
import (
"net/http"
)
2021-02-20 22:35:16 +00:00
func serveBlogStats(blog, statsPath string) func(http.ResponseWriter, *http.Request) {
2021-01-04 19:29:49 +00:00
return func(w http.ResponseWriter, r *http.Request) {
2021-01-15 20:56:46 +00:00
// Build query
2021-01-30 18:35:48 +00:00
query, params := buildPostsQuery(&postsRequestConfig{
2021-01-15 20:56:46 +00:00
blog: blog,
status: statusPublished,
})
// Count total posts
row, err := appDbQueryRow("select count(distinct path) from ("+query+")", params...)
2021-01-04 19:29:49 +00:00
if err != nil {
serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
2021-01-15 20:56:46 +00:00
var totalCount int
2021-02-08 17:51:07 +00:00
if err = row.Scan(&totalCount); err != nil {
2021-01-04 19:29:49 +00:00
serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
2021-01-15 20:56:46 +00:00
// Count posts per year
2021-02-08 17:51:07 +00:00
rows, err := appDbQuery("select substr(published, 1, 4) as year, count(distinct path) as count from ("+query+") where published != '' group by year order by year desc", params...)
2021-01-04 19:29:49 +00:00
if err != nil {
serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
2021-01-15 20:56:46 +00:00
var years, counts []int
2021-01-04 19:29:49 +00:00
for rows.Next() {
var year, count int
2021-02-08 17:51:07 +00:00
if err = rows.Scan(&year, &count); err == nil {
years = append(years, year)
counts = append(counts, count)
}
2021-01-04 19:29:49 +00:00
}
2021-02-20 22:35:16 +00:00
render(w, r, templateBlogStats, &renderData{
2021-01-17 11:53:07 +00:00
BlogString: blog,
2021-01-04 19:29:49 +00:00
Canonical: statsPath,
Data: map[string]interface{}{
"total": totalCount,
"years": years,
"counts": counts,
},
})
}
}