1package middleware
2
3import (
4 "log"
5 "net/http"
6 "strconv"
7
8 "tangled.org/core/appview/pagination"
9)
10
11func Paginate(next http.Handler) http.Handler {
12 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
13 page := pagination.FirstPage()
14
15 offsetVal := r.URL.Query().Get("offset")
16 if offsetVal != "" {
17 offset, err := strconv.Atoi(offsetVal)
18 if err != nil {
19 log.Println("invalid offset")
20 } else {
21 page.Offset = offset
22 }
23 }
24
25 limitVal := r.URL.Query().Get("limit")
26 if limitVal != "" {
27 limit, err := strconv.Atoi(limitVal)
28 if err != nil {
29 log.Println("invalid limit")
30 } else {
31 page.Limit = limit
32 }
33 }
34
35 ctx := pagination.IntoContext(r.Context(), page)
36 next.ServeHTTP(w, r.WithContext(ctx))
37 })
38}