Created
April 26, 2021 11:52
-
-
Save dipeshhkc/f6d1b8777a626dffbc04ffc936c33aff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//StatusInList -> checks if the given status is in the list | |
func StatusInList(status int, statusList []int) bool { | |
for _, i := range statusList { | |
if i == status { | |
return true | |
} | |
} | |
return false | |
} | |
// DBTransactionMiddleware : to setup the database transaction middleware | |
func DBTransactionMiddleware(db *gorm.DB) gin.HandlerFunc { | |
return func(c *gin.Context) { | |
txHandle := db.Begin() | |
log.Print("beginning database transaction") | |
defer func() { | |
if r := recover(); r != nil { | |
txHandle.Rollback() | |
} | |
}() | |
c.Set("db_trx", txHandle) | |
c.Next() | |
if StatusInList(c.Writer.Status(), []int{http.StatusOK, http.StatusCreated}) { | |
log.Print("committing transactions") | |
if err := txHandle.Commit().Error; err != nil { | |
log.Print("trx commit error: ", err) | |
} | |
} else { | |
log.Print("rolling back transaction due to status code: ", c.Writer.Status()) | |
txHandle.Rollback() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment