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
ruby
module RequestTagging class Middleware def initialize(app) @app = app
Per-request context with CurrentAttributes in Rails
middleware
thread-safety
logging
Intermediate
7 steps
go
package hashring import ( "hash/crc32"
How consistent hashing works in Go
consistent-hashing
load-balancing
concurrency
Intermediate
8 steps
typescript
type Middleware<TIn, TOut> = (ctx: TIn) => Promise<TOut> | TOut; class Pipeline<TIn, TOut> { private constructor(private readonly run: Middleware<TIn, TOut>) {}
A type-safe async middleware pipeline
generics
type-safety
middleware
Advanced
9 steps
php
<?php namespace App\Http\Middleware;
Caching HTTP responses with Laravel middleware
middleware
caching
http
Intermediate
8 steps
rust
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; #[derive(Debug)]
Parsing an HTTP Range header in Rust
http-range
parsing
file-io
Intermediate
10 steps
go
package handlers import ( "encoding/base64"
Cursor pagination in a Gin handler
pagination
cursor
rest-api
Intermediate
8 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.