pagination.go 952 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package middleware
  2. import (
  3. "net/http"
  4. "strconv"
  5. )
  6. // PaginatedHandlerFunc is a handler for endpoints that require pagination.
  7. type PaginatedHandlerFunc func(int, int, http.ResponseWriter, *http.Request)
  8. // HandlePagination is a middleware handler that pulls pagination values
  9. // and passes them along.
  10. func HandlePagination(handler PaginatedHandlerFunc) http.HandlerFunc {
  11. return func(w http.ResponseWriter, r *http.Request) {
  12. // Default 50 items per page
  13. limitString := r.URL.Query().Get("limit")
  14. if limitString == "" {
  15. limitString = "50"
  16. }
  17. limit, err := strconv.Atoi(limitString)
  18. if err != nil {
  19. w.WriteHeader(http.StatusBadRequest)
  20. return
  21. }
  22. // Default first page 0
  23. offsetString := r.URL.Query().Get("offset")
  24. if offsetString == "" {
  25. offsetString = "0"
  26. }
  27. offset, err := strconv.Atoi(offsetString)
  28. if err != nil {
  29. w.WriteHeader(http.StatusBadRequest)
  30. return
  31. }
  32. handler(offset, limit, w, r)
  33. }
  34. }