'can't have email on existing user golang
I'm trying to check if an user already have a email. I wrote a function like this :
func IsUniqueEmail(body io.ReadCloser) (database.User, error) {
connection := database.GetDatabase()
defer database.CloseDatabase(connection)
var user database.User
err := json.NewDecoder(body).Decode(&user)
if err != nil {
return user, err
}
var dbuser database.User
connection.Where("email = ?", user.Email).First(&dbuser)
fmt.Println("User: ", dbuser)
fmt.Println("User: ", dbuser.Email)
return dbuser, nil}
but the fmt.Println show me
User: {{0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC } }
I assume where is no email in dbuser but I can't understand why anyone have an idea ? Cheers
Solution 1:[1]
If you are using gorm v2, you can catch the record not found error
var dbuser database.User
err := connection.Where("email = ?", user.Email).First(&dbuser).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return dbuser, err
}
fmt.Println("User: ", dbuser)
fmt.Println("User: ", dbuser.Email)
return dbuser, nil}
Solution 2:[2]
The solution
func IsUniqueEmail(body io.ReadCloser) (database.User, bool, error) {
var dbuser database.User
connection := database.GetDatabase()
defer database.CloseDatabase(connection)
var user database.User
err := json.NewDecoder(body).Decode(&user)
if err != nil {
return user, false, err
}
errDB := connection.Where("email = ?", user.Email).First(&dbuser).Error
if errors.Is(errDB, gorm.ErrRecordNotFound) {
return dbuser, true, errDB
}
if dbuser.Email != "" {
return dbuser, false, nil
}
return user, true, nil
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Santiago |
Solution 2 | Rémi boivin |