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 streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
go
package httputil import ( "net"
Safely extracting the real client IP in Go
security
http
ip-spoofing
Intermediate
7 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.