I understand that one should unlock a mutex using defer in case an error comes up. Otherwise, if you left the mutex locked, other goroutines would be blocked if they tried to access it. But what I don't understand is if I was to remove or comment out the h.db.Mutex.Unlock(), then there will be no http response sent back to the client. Again, I understand leaving a mutex locked would block other goroutines from aquiring the lock and it would be very silly to not unlock a mutex, but why would it block the goroutine that FIRST acquired the lock from being able to send an http response?
type HandlerWrapper struct {
db *sql.DB
dbMutex *sync.Mutex
}
handlerWrapper := HandlerWrapper{db : db, dbMutex: &sync.Mutex{}}
// using go chi router
router.Get("/items", handlerWrapper.GetAllHandler)
http.ListenAndServe(":5000", router)
func (h *HandlerWrapper) GetAllHandler(w http.ResponseWriter, r *http.Request){
h.dbMutex.Lock()
//defer h.dbMutex.Unlock() // if this is commented, no http response, why?
rows, err := h.db.Query("SELECT * FROM lst") // this line returns an error intentionally
if err != nil {
log.Printf(": %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}