第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

QueryRow 上的無效內(nèi)存地址或 nil 指針取消引用

QueryRow 上的無效內(nèi)存地址或 nil 指針取消引用

Go
阿晨1998 2022-05-17 16:58:46
我是新來的,試圖創(chuàng)建一個登錄函數(shù),當(dāng)試圖從數(shù)據(jù)庫中查詢行時,我收到了這個錯誤: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 不為空,我不明白是什么導(dǎo)致了這個錯誤。
查看完整描述

1 回答

?
白衣非少年

TA貢獻(xiàn)1155條經(jīng)驗 獲得超0個贊

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

    // ...

    result := db.QueryRow(...)

db大概是nil因為sql.Open失敗了。


err != nil當(dāng)一個函數(shù)返回一個error類型時,你不會像你應(yīng)該做的那樣檢查。


查看完整回答
反對 回復(fù) 2022-05-17
  • 1 回答
  • 0 關(guān)注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號