Pagination is a common requirement for web applications to efficiently display large sets of data in manageable chunks. This example demonstrates how to implement pagination using the Fiber framework in Go.
package main
import (
"github.com/gofiber/fiber/v2"
"math"
)
func main() {
app := fiber.New()
app.Get("/items", func(c *fiber.Ctx) error {
// Sample data
items := make([]string, 100) // Simulating 100 data items
for i := 0; i < 100; i++ {
items[i] = "Item " + strconv.Itoa(i+1)
}
// Pagination parameters
page, _ := strconv.Atoi(c.Query("page", "1"))
limit, _ := strconv.Atoi(c.Query("limit", "10"))
offset := (page - 1) * limit
// Calculate total pages
total := len(items)
totalPages := int(math.Ceil(float64(total) / float64(limit)))
// Create paged items
if offset > total {
return c.Status(404).SendString("Page not found")
}
end := offset + limit
if end > total {
end = total
}
return c.JSON(fiber.Map{
"page": page,
"total": total,
"totalPages": totalPages,
"items": items[offset:end],
})
})
app.Listen(":3000")
}
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?