I am trying to run multiple goroutines that modify the same variable passed by reference.
But I am sure the way I have implemented this is functionally incorrect. Even though it seems to be working in my tests, I have a feeling this pattern would end the parent function when the first goroutine completes if the second goroutine takes considerably longer to run than the first one.
I would like your input/suggestions/advice.
package auth
import (
"regexp"
zxcvbn "github.com/nbutton23/zxcvbn-go"
"golang.org/x/net/context"
)
type AuthService struct{}
func NewAuthService() *AuthService {
return &AuthService{}
}
func (this *AuthService) ValidateCredentials(ctx context.Context, req *ValidateCredentialsRequest) (*ValidateCredentialsResponse, error) {
c := make(chan *ValidateCredentialsResponse)
go validatePassword(req.GetPassword(), c)
go validateUsername(req.GetUsername(), c)
c <- &ValidateCredentialsResponse{IsValid: true}
return <-c, nil
}
func validateUsername(email string, c chan *ValidateCredentialsResponse) {
for {
res := <-c
if email == "" {
res.IsValid = false
res.Username = "Please provide your email address."
} else if len(email) > 128 {
res.IsValid = false
res.Username = "Email address can not exceed 128 characters."
} else if !regexp.MustCompile(`.+@.+`).MatchString(email) {
res.IsValid = false
res.Username = "Please enter a valid email address."
}
c <- res
}
}
func validatePassword(password string, c chan *ValidateCredentialsResponse) {
for {
res := <-c
if password == "" {
res.IsValid = false
res.Password = "Please provide your password."
} else {
quality := zxcvbn.PasswordStrength(password, []string{})
if quality.Score < 3 {
res.IsValid = false
res.Password = "Your password is weak."
}
}
c <- res
}
}