How do I paginate results with Fiber in Go?

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") }

pagination Fiber Go web application data display