比较Golang中的错误

比较Golang中的错误

问题描述:

I'm writing a basic password authentication system in golang.
I use bcrypt to hash the password and save the hash in a database.
Here's the function to retrieve an authenticated account from the database.

func FindAccount(db *gorp.DbMap, email, password string) (*Account, error) {
    account, err := FindByEmail(db, email)
    if err != nil {
        return nil, err
    }
    if account == nil {
        return nil, nil
    }
    if err := bcrypt.CompareHashAndPassword([]byte(account.HashedPassword), []byte(password)); err != nil {
        return nil, err
    }
    return account, nil
}

And the caller:

account, err := FindAccount(db, email, password)
if err != nil {
    if err == bcrypt.ErrMismatchedHashAndPassword {
        log.Printf("Why doesn't this condition match?")
        return nil, EmailPasswordInvalidError{}
    }

    log.Printf("bcrypt.Err: %p, %#v", bcrypt.ErrMismatchedHashAndPassword, bcrypt.ErrMismatchedHashAndPassword)
    log.Printf("err       : %p, %#v", err, err)
    return nil, err
}

And when I use this code and provide invalid email and password, here's what happens:

sessions.go:51: bcrypt.Err: 0xc2080290b0, &errors.errorString{s:"crypto/bcrypt: hashedPassword is not the hash of the given password"}
sessions.go:52: err       : 0xc2080291e0, &errors.errorString{s:"crypto/bcrypt: hashedPassword is not the hash of the given password"}

Why is the pointer address different? Can't we just compare errors?

I had two bcrypt packages imported.. The file which has FindAccount imported "code.google.com/p/go.crypto/bcrypt", and the caller imported "golang.org/x/crypto/bcrypt".

Thus there were multiple

var ErrMismatchedHashAndPassword = errors.New("crypto/bcrypt: hashedPassword is not the hash of the given password")

with different pointers.

Replacing all "code.google.com/p/go.crypto/bcrypt" with "golang.org/x/crypto/bcrypt" fixed the issue.