DEV Community

Saransh Agrawal
Saransh Agrawal

Posted on

Database transactional in Go controller

Hey everyone!! can someone tell me or provide me the resources for handling transactional in go language controller. Like we handle in java springboot with annotation @Transactional.

Top comments (1)

Collapse
 
sazardev profile image
Sazardev

Hi there! Firstly you need to use the package database/sql (use Go mod)

And sadly, unlike java spring, there's not a tag like @Transactional, you need to do it. using any Error handler or using Panic. But if you want to use a simple way, just detect an error and then do a .Rollback() and that's all!

func RollbackHandler(w http.ResponseWriter, r *http.Request) {
    tx, err := db.Begin()
    if err != nil {
        return
    }

    defer func() {
        if err != nil {
            tx.Rollback()
            return
        }
        err = tx.Commit()
        if err != nil {
            log.Fatal(err)
        }
    }()
}
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more