Hi guys I'm trying to make multiple requests to a database, and I found doing them in order synchronously is quite slow and exponentially increases response time while waiting for each request to finish, this is what I have so far:
var wg sync.WaitGroup
dbUsername := make(chan string, 1)
dbEmail := make(chan string, 1)
wg.Add(2)
go func(username chan string, waiter sync.WaitGroup) {
defer waiter.Done()
err = db.QueryRow("SELECT username FROM user WHERE username = ?", vals.Get("username")).Scan(&result)
if err != nil {
log.Println(err)
}
}(dbUsername, wg)
go func(email chan string, waiter sync.WaitGroup) {
defer waiter.Done()
err = db.QueryRow("SELECT email FROM user WHERE email = ?", vals.Get("email")).Scan(&result)
if err != nil {
log.Println(err)
}
}(dbEmail, wg)
wg.Wait()
if <-dbUsername != "" {
formErrors = append(formErrors, "Username has already been taken.")
}
if <-dbEmail != "" {
formErrors = append(formErrors, "Email has already been taken.")
}
but it doesn't seem to work correctly, I've followed the WaitGroup
example to the dot, but it seems to hang on wg.Wait()
and I'm not sure why. And is there a prettier way to do this or is what I have mocked up normal?
also small sub question:
is it possible to declare a buffered channel with var
e.g. var blah chan string 1