diff options
| -rw-r--r-- | backend/data.go | 2 | ||||
| -rw-r--r-- | backend/home.go | 29 | ||||
| -rw-r--r-- | backend/templates/home.html | 8 |
3 files changed, 33 insertions, 6 deletions
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 @@ </p> </article> {{ end }} + {{ if ne .PagesNumber 1 }} <div class="pagination"> - <a href="">Précédent</a> - <p>01/15</p> - <a href="">Suivant</a> + {{ if ne .CurrentPage 1 }}<a href="?page={{ before .CurrentPage }}">Précédent</a>{{else}}<p></p>{{end}} + <p>{{ .CurrentPage }}/{{ .PagesNumber }}</p> + {{ if ne .CurrentPage .PagesNumber }}<a href="?page={{ next .CurrentPage }}">Suivant</a>{{else}}<p></p>{{end}} </div> + {{ end }} </article> {{end}}
\ No newline at end of file |
