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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Clamping user-supplied paging and sort values to safe defaults prevents abuse and invalid queries.
- 2Injecting the database via a closure keeps handlers testable and avoids global state.
- 3Returning pagination metadata alongside data lets clients navigate without guessing.
Related explainers
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
go
package middleware import ( "net/http"
A maintenance-mode gate in Gin
middleware
atomic-flag
concurrency
Intermediate
8 steps
go
func ServeVideo(c *gin.Context) { id := c.Param("id") video, err := videoRepo.FindByID(c.Request.Context(), id) if err != nil {
Streaming video files with Gin
http streaming
range requests
file serving
Intermediate
6 steps
go
package handler type LineItem struct { SKU string `json:"sku" binding:"required,alphanum"`
Structured validation errors in Gin
validation
json-binding
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-paginated-list-endpoint-in-gin-explained-go-b9f2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.