go 49 lines · 8 steps

Wrapping Gin requests in a DB transaction

A Gin middleware that opens a GORM transaction per request and commits or rolls back based on the outcome.

Explained by highlit
1package middleware
2 
3import (
4 "net/http"
5 
6 "github.com/gin-gonic/gin"
7 "gorm.io/gorm"
8)
9 
10const txContextKey = "db_tx"
11 
12func Transactional(db *gorm.DB) gin.HandlerFunc {
13 return func(c *gin.Context) {
14 tx := db.Begin()
15 if tx.Error != nil {
16 c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
17 "error": "could not start transaction",
18 })
19 return
20 }
21 
22 c.Set(txContextKey, tx)
23 
24 defer func() {
25 if r := recover(); r != nil {
26 tx.Rollback()
27 panic(r)
28 }
29 
30 if len(c.Errors) > 0 || c.Writer.Status() >= http.StatusBadRequest {
31 tx.Rollback()
32 return
33 }
34 
35 if err := tx.Commit().Error; err != nil {
36 _ = c.Error(err)
37 c.JSON(http.StatusInternalServerError, gin.H{
38 "error": "could not commit transaction",
39 })
40 }
41 }()
42 
43 c.Next()
44 }
45}
46 
47func TxFromContext(c *gin.Context) *gorm.DB {
48 return c.MustGet(txContextKey).(*gorm.DB)
49}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Middleware can bracket a handler's whole lifecycle by pairing setup before c.Next() with cleanup in a deferred closure.
  2. 2Deciding commit-versus-rollback from the response status and c.Errors keeps handlers free of transaction boilerplate.
  3. 3Re-panicking after rollback preserves crash behavior while still guaranteeing the transaction is released.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Wrapping Gin requests in a DB transaction — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code