比较Golang中的错误

3
我正在使用golang编写基本的密码认证系统。
我使用bcrypt对密码进行哈希处理,并将哈希值保存在数据库中。
以下是从数据库中检索经过身份验证的帐户的函数。
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
}

以及呼叫者:

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
}

当我使用此代码并提供无效的电子邮件和密码时,会发生以下情况:

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"}

为什么指针地址不同?我们不能只比较错误吗?
1个回答

4

我导入了两个bcrypt包。

FindAccount所在的文件导入了"code.google.com/p/go.crypto/bcrypt",而调用方则导入了"golang.org/x/crypto/bcrypt"

因此存在多个...

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

使用不同的指针。
将所有的"code.google.com/p/go.crypto/bcrypt"替换为"golang.org/x/crypto/bcrypt"即可解决问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接