From 0bcfe1f7df5c309f8a4ab381a6fd5b772d929542 Mon Sep 17 00:00:00 2001 From: Anhgelus Morhtuuzh Date: Thu, 2 Oct 2025 22:54:46 +0200 Subject: feat(backend): working pagination --- backend/data.go | 2 ++ backend/home.go | 29 ++++++++++++++++++++++++++--- backend/templates/home.html | 8 +++++--- 3 files changed, 33 insertions(+), 6 deletions(-) (limited to 'backend') diff --git a/backend/data.go b/backend/data.go index f3e8b42..9c30c6b 100644 --- a/backend/data.go +++ b/backend/data.go @@ -64,6 +64,8 @@ func (d *data) handleGeneric(w http.ResponseWriter, r *http.Request, name string } return fmt.Sprintf("/assets/%s", path) }, + "next": func(i int) int { return i + 1 }, + "before": func(i int) int { return i - 1 }, }).ParseFS(templates, fmt.Sprintf("templates/%s.html", name), "templates/base.html") if err != nil { panic(err) diff --git a/backend/home.go b/backend/home.go index 32634a1..43ace8a 100644 --- a/backend/home.go +++ b/backend/home.go @@ -1,19 +1,25 @@ package backend import ( + "log/slog" "maps" "net/http" "slices" + "strconv" "time" "github.com/go-chi/chi/v5" ) +const maxLogsPerPage = 5 + var sortedLogs []*logData type homeData struct { *data - Logs []*logData + Logs []*logData + PagesNumber int + CurrentPage int } func (h *homeData) SetData(d *data) { @@ -22,18 +28,35 @@ func (h *homeData) SetData(d *data) { func HandleHome(r *chi.Mux) { r.Get("/", func(w http.ResponseWriter, r *http.Request) { + rawPage := r.URL.Query().Get("page") + page := 1 + if rawPage != "" { + var err error + page, err = strconv.Atoi(rawPage) + if err != nil || page < 1 { + slog.Warn("invalid page number", "rawPage", rawPage) + w.WriteHeader(http.StatusBadRequest) + return + } + } d := new(homeData) d.data = new(data) if sortedLogs == nil { sortLogs() } - d.Logs = sortedLogs + d.CurrentPage = page + d.PagesNumber = len(sortedLogs)/maxLogsPerPage + 1 + if d.PagesNumber < page { + http.NotFoundHandler().ServeHTTP(w, r) + return + } + d.Logs = sortedLogs[(page-1)*maxLogsPerPage : min(page*maxLogsPerPage, len(sortedLogs))] d.handleGeneric(w, r, "home", d) }) } func sortLogs() { - slices.SortedFunc(maps.Values(logs), func(l *logData, l2 *logData) int { + sortedLogs = slices.SortedFunc(maps.Values(logs), func(l *logData, l2 *logData) int { lt := l.pubDate.AsTime(time.UTC) l2t := l2.pubDate.AsTime(time.UTC) // we want it reversed diff --git a/backend/templates/home.html b/backend/templates/home.html index f0b9b9c..37236ba 100644 --- a/backend/templates/home.html +++ b/backend/templates/home.html @@ -18,10 +18,12 @@

{{ end }} + {{ if ne .PagesNumber 1 }} + {{ end }} {{end}} \ No newline at end of file -- cgit v1.2.3