Skip to content

Instantly share code, notes, and snippets.

Forked from lyoshenka/tx.go
Created September 17, 2017 10:33
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
A simple, neat way to wrap code in an sql transaction with proper committing/rollbacking and error handling.
// TxFunc is a function that can be wrapped in a transaction
type TxFunc func(tx *sql.Tx) error
// WithTx wraps a function in an sql transaction. After the function returns, the transaction is
// committed if there's no error, or rolled back if there is one.
func WithTx(db *sql.DB, f TxFunc) (err error) {
tx, err := db.Begin()
if err != nil {
return err
defer func() {
if p := recover(); p != nil {
} else if err != nil {
} else {
err = tx.Commit()
return f(tx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment