github.com/lovung/GoCleanArchitecture@v0.0.0-20210302152432-50d91fd29f9f/app/internal/interface/restful/middleware/transaction_middleware.go (about)

     1  package middleware
     2  
     3  import (
     4  	"github.com/lovung/GoCleanArchitecture/app/internal/appctx"
     5  	"github.com/lovung/GoCleanArchitecture/app/internal/transaction"
     6  	"github.com/lovung/GoCleanArchitecture/pkg/logger"
     7  
     8  	"github.com/gin-gonic/gin"
     9  )
    10  
    11  // TransactionMiddleware middleware to help manage the transaction
    12  type TransactionMiddleware struct {
    13  	manager transaction.Manager
    14  }
    15  
    16  // NewTransactionMiddleware contructor
    17  func NewTransactionMiddleware(manager transaction.Manager) TransactionMiddleware {
    18  	return TransactionMiddleware{
    19  		manager: manager,
    20  	}
    21  }
    22  
    23  // StartRequest start the transaction in the beginning of a request
    24  func (mw *TransactionMiddleware) StartRequest(ctx *gin.Context) {
    25  	newCtx := mw.manager.TxnBegin(ctx.Request.Context())
    26  	ctx.Request = ctx.Request.WithContext(newCtx)
    27  	ctx.Next()
    28  }
    29  
    30  // EndRequest get error to check if need to commit or rollback
    31  func (mw *TransactionMiddleware) EndRequest(ctx *gin.Context) {
    32  	ctx.Next()
    33  	err := appctx.GetValue(ctx.Request.Context(), appctx.ErrorContextKey)
    34  	if p := recover(); p != nil {
    35  		logger.Error("found p and rollback ", p)
    36  		mw.manager.TxnRollback(ctx.Request.Context())
    37  	} else if err != nil {
    38  		logger.Debugf("found e and rollback %v", err)
    39  		mw.manager.TxnRollback(ctx.Request.Context())
    40  	} else {
    41  		logger.Debugf("commit transaction %p", mw.manager.GetTxn(ctx.Request.Context()))
    42  		mw.manager.TxnCommit(ctx.Request.Context())
    43  	}
    44  }