go 48 lines · 8 steps

Building a paginated list endpoint in Gin

A Gin handler that safely parses pagination and sort params, then queries GORM with offset-based paging and returns metadata.

Explained by highlit
1func ListArticles(db *gorm.DB) gin.HandlerFunc {
2 return func(c *gin.Context) {
3 page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
4 if err != nil || page < 1 {
5 page = 1
6 }
7 
8 pageSize, err := strconv.Atoi(c.DefaultQuery("page_size", "20"))
9 if err != nil || pageSize < 1 {
10 pageSize = 20
11 }
12 if pageSize > 100 {
13 pageSize = 100
14 }
15 
16 sort := c.DefaultQuery("sort", "created_at desc")
17 if !allowedSorts[sort] {
18 sort = "created_at desc"
19 }
20 
21 query := db.Model(&Article{})
22 if status := c.Query("status"); status != "" {
23 query = query.Where("status = ?", status)
24 }
25 
26 var total int64
27 if err := query.Count(&total).Error; err != nil {
28 c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to count articles"})
29 return
30 }
31 
32 var articles []Article
33 if err := query.Order(sort).Offset((page - 1) * pageSize).Limit(pageSize).Find(&articles).Error; err != nil {
34 c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to fetch articles"})
35 return
36 }
37 
38 c.JSON(http.StatusOK, gin.H{
39 "data": articles,
40 "meta": gin.H{
41 "page": page,
42 "page_size": pageSize,
43 "total": total,
44 "total_pages": (total + int64(pageSize) - 1) / int64(pageSize),
45 },
46 })
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Clamping user-supplied paging and sort values to safe defaults prevents abuse and invalid queries.
  2. 2Injecting the database via a closure keeps handlers testable and avoids global state.
  3. 3Returning pagination metadata alongside data lets clients navigate without guessing.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a paginated list endpoint in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code