gpt4 book ai didi

go - 无效的内存地址或QueryRow上的nil指针取消引用

转载 作者:行者123 更新时间:2023-12-01 22:38:47 25 4
gpt4 key购买 nike

我是新手,尝试创建登录功能,尝试从数据库查询行时出现此错误:runtime error: invalid memory address or nil pointer dere
ference

此行导致的崩溃:

    result := db.QueryRow("SELECT password FROM users WHERE email=$1", credentials.Email)

这是代码:
    type Credentials struct {
Email string `json:"email", db:"email"`
Password string `json:"password", db:"password"`
}

func SignIn(w http.ResponseWriter, r *http.Request) {
credentials := &Credentials{}
err := json.NewDecoder(r.Body).Decode(credentials)
if err != nil {
// If there is something wrong with the request body, return a 400 status
w.WriteHeader(http.StatusBadRequest)
return
}

psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+"dbname=%s sslmode=disable", dbInfo.Host, dbInfo.Port, dbInfo.User, dbInfo.DBname)
db, err := sql.Open("postgres", psqlInfo)

println(credentials.Email)
result := db.QueryRow("SELECT password FROM users WHERE email=$1", credentials.Email)
defer db.Close()
if err != nil {
//If there is an issue with the database, return a 500 error.
w.WriteHeader(http.StatusInternalServerError)
return
}

//We create another instance of 'Credentials' t store the credentials we get from the database
storedCreds := &Credentials{}

// Store the obtained password in `storedCreds`
err = result.Scan(&storedCreds.Password)
if err != nil {
// If an entry with the email does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusUnauthorized)
return
}

//If the error is of any other type, send a 500 status
w.WriteHeader(http.StatusInternalServerError)
return
}

if credentials.Password != storedCreds.Password {
//The two passwords does not match, return a 401 status
w.WriteHeader(http.StatusUnauthorized)
}
}

我检查了凭据,电子邮件不为空,并且我不明白是什么导致了此错误。

最佳答案

    db, err := sql.Open("postgres", psqlInfo)
// ...
result := db.QueryRow(...)
db可能是 nil,因为 sql.Open 失败。

您不会像在函数返回 err != nil类型时始终应该检查的那样检查 error

关于go - 无效的内存地址或QueryRow上的nil指针取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60115707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com