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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?