go 55 lines · 9 steps

Injecting a scoped GORM query via Gin middleware

A Gin middleware pre-builds a soft-delete-aware GORM session and hands it to every handler in a route group.

Explained by highlit
1package middleware
2 
3import (
4 "github.com/gin-gonic/gin"
5 "gorm.io/gorm"
6)
7 
8const scopedDBKey = "scopedDB"
9 
10func InjectActiveScope(db *gorm.DB) gin.HandlerFunc {
11 return func(c *gin.Context) {
12 scoped := db.WithContext(c.Request.Context()).
13 Where("deleted_at IS NULL").
14 Session(&gorm.Session{NewDB: true})
15 
16 c.Set(scopedDBKey, scoped)
17 c.Next()
18 }
19}
20 
21func ScopedDB(c *gin.Context) *gorm.DB {
22 if v, ok := c.Get(scopedDBKey); ok {
23 if db, ok := v.(*gorm.DB); ok {
24 return db
25 }
26 }
27 panic("scopedDB not present: InjectActiveScope middleware missing on this route group")
28}
29 
30func RegisterArticleRoutes(r *gin.Engine, db *gorm.DB) {
31 articles := r.Group("/articles", InjectActiveScope(db))
32 
33 articles.GET("", func(c *gin.Context) {
34 var list []Article
35 if err := ScopedDB(c).Order("published_at DESC").Find(&list).Error; err != nil {
36 c.JSON(500, gin.H{"error": "failed to load articles"})
37 return
38 }
39 c.JSON(200, list)
40 })
41 
42 articles.GET("/:id", func(c *gin.Context) {
43 var article Article
44 err := ScopedDB(c).First(&article, "id = ?", c.Param("id")).Error
45 if err == gorm.ErrRecordNotFound {
46 c.JSON(404, gin.H{"error": "not found"})
47 return
48 }
49 if err != nil {
50 c.JSON(500, gin.H{"error": "lookup failed"})
51 return
52 }
53 c.JSON(200, article)
54 })
55}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Middleware can precompute a request-scoped dependency and stash it in the context for handlers to reuse.
  2. 2Building a GORM session once with a base filter keeps soft-delete logic in one place instead of every query.
  3. 3A typed accessor that panics on a missing key turns a wiring mistake into a loud, immediate failure.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Injecting a scoped GORM query via Gin middleware — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code