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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Middleware can precompute a request-scoped dependency and stash it in the context for handlers to reuse.
- 2Building a GORM session once with a base filter keeps soft-delete logic in one place instead of every query.
- 3A typed accessor that panics on a missing key turns a wiring mistake into a loud, immediate failure.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 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/injecting-a-scoped-gorm-query-via-gin-middleware-explained-go-3e87/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.