How do I paginate results with Chi in Go?

If you want to paginate results in your Go application using the Chi router, you can follow this simple example below:

package main import ( "github.com/go-chi/chi/v5" "net/http" "strconv" ) // Sample data (for demonstration) var items = make([]string, 100) for i := 0; i < 100; i++ { items[i] = "Item " + strconv.Itoa(i+1) } func main() { r := chi.NewRouter() r.Get("/items", func(w http.ResponseWriter, r *http.Request) { page := r.URL.Query().Get("page") itemsPerPage := 10 pageNumber, err := strconv.Atoi(page) if err != nil || pageNumber < 1 { pageNumber = 1 } start := (pageNumber - 1) * itemsPerPage end := start + itemsPerPage if end > len(items) { end = len(items) } w.Write([]byte("
    ")) for _, item := range items[start:end] { w.Write([]byte("
  • " + item + "
  • ")) } w.Write([]byte("
")) // Display pagination totalPages := (len(items) + itemsPerPage - 1) / itemsPerPage if pageNumber > 1 { w.Write([]byte("Previous ")) } if pageNumber < totalPages { w.Write([]byte("Next")) } w.Write([]byte("")) }) http.ListenAndServe(":8080", r) }

Chi Go Pagination Web Development HTTP Router REST API