为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
阿晨1998 2022-05-17 16:58:46
我是新来的,试图创建一个登录函数,当试图从数据库中查询行时,我收到了这个错误:runtime error: invalid memory address or nil pointer dereference此行引起的崩溃:    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)    }}我检查了credentials.Email 不为空,我不明白是什么导致了这个错误。
查看完整描述

1 回答

?
白衣非少年

TA贡献1155条经验 获得超0个赞

 db, err := sql.Open("postgres", psqlInfo)

    // ...

    result := db.QueryRow(...)

db大概是nil因为sql.Open失败了。


err != nil当一个函数返回一个error类型时,你不会像你应该做的那样检查。


查看完整回答
反对 回复 2022-05-17
  • 1 回答
  • 0 关注
  • 153 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号