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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Middleware can bracket a handler's whole lifecycle by pairing setup before c.Next() with cleanup in a deferred closure.
- 2Deciding commit-versus-rollback from the response status and c.Errors keeps handlers free of transaction boilerplate.
- 3Re-panicking after rollback preserves crash behavior while still guaranteeing the transaction is released.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 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/wrapping-gin-requests-in-a-db-transaction-explained-go-e02f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.