Skip to content

Instantly share code, notes, and snippets.

@dipeshhkc
Created April 26, 2021 11:52
Show Gist options
  • Save dipeshhkc/f6d1b8777a626dffbc04ffc936c33aff to your computer and use it in GitHub Desktop.
Save dipeshhkc/f6d1b8777a626dffbc04ffc936c33aff to your computer and use it in GitHub Desktop.
//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