Does this webapp code need synchronization?

Issue

I’m learning Go at the moment and this is the code for a web-app I’m writing:

func init() {

    db, err := sql.Open("mysql", "master:123456@/shopping_list")

    if err != nil {
        panic(err.Error())
    }

    http.HandleFunc("/sql", func(w http.ResponseWriter, r *http.Request) {
        sqlHandler(w, r, db)
    })

}

sqlHandler() reads a record from a table in shopping_list, edits it and then updates the record.

Now as I understand it, each request runs on a separate goroutine and that mysql locks a record while it is being read or written. So, in this case, does this code need any synchronization?

Solution

Short answer: no.

You don’t need to explicitly synchronise your code, because calls to any method on db that require a lock will simply block until the lock is released. In other words, synchronisation is taken care of by the package that actually needs the synchronisation.


As a side note, I would suggest to run your code through gofmt, which will make other Go nuts who read your code happy.

Answered By – Attila O.

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.