douyazi1129 2018-11-08 22:06
浏览 80
已采纳

如何在Go中正确绑定postgresql变量?

I have this function that is returning an error sql: Rows are closed. I can't figure out why...

Here is the function :

func GetUserFromToken(db *sql.DB, token string) User {
    query := `
        SELECT id, token, name, surname, phone, email FROM users WHERE token=$1
        `

    rows, err := db.Query(query, token)
    if err != nil {
        fmt.Println("query error : " + err.Error())
    }

    var user User
    rows.Next()
    err = rows.Scan(&user.ID, &user.Token, &user.Name, &user.Surname, &user.Phone, &user.Email)
    if err != nil {
        fmt.Println("scan error : " + err.Error())
    }

    return user
}

When I log the token it's the proper token. When I hard code the token in the query for testing purposes, it works fine. For instance :

query := `
        SELECT id, token, name, surname, phone, email FROM users WHERE token='abcdefg12345'
        `

Tried also to set the query such as :

query := "SELECT id, token, name, surname, phone, email FROM users WHERE token = $1"

row := db.QueryRow(query, "abcdefg12345")

It works fine. fmt.Println(token) prints abcdefg12345.

Would someone help me understand what I'm missing ?


UPDATE : found my fail.

So the token I had was the bearer token extracted from the header with the following function :

func GetBearerToken(r *http.Request) string {
    reqToken := r.Header.Get("Authorization")
    splitToken := strings.Split(reqToken, "Bearer")
    reqToken = splitToken[1]
    return reqToken
}

Had a leading whitespace that I did not notice in my fmt.Println. After a good night of sleep thinking about @RayfenWindspear's comment I had this urging to check string length then I saw the fail. Feeling a bit idiotic and amused at the same time that I didn't catch it.

So my simple fix : from: reqToken = splitToken[1] to : strings.TrimSpace(splitToken[1])

  • 写回答

1条回答 默认 最新

  • dongyun9120 2018-11-08 23:15
    关注

    Here's how you'd write this code. The err returned will be sql.ErrNoRows if nothing was returned. Let me know how this works, and then maybe I can give other debugging steps.

    func GetUserFromToken(db *sql.DB, token string) (u User, err error) {
      err = db.QueryRow(
        "SELECT id, token, name, surname, phone, email FROM users WHERE token=$1",
        token,
      ).Scan(
        &u.ID,
        &u.Token,
        &u.Name,
        &u.Surname,
        &u.Phone,
        &u.Email)
      return
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序