不能从db.QueryRow()推断出err

时间:2019-09-17 08:04:12

标签: postgresql go pq

我正在尝试实现一个简单的POST API,以在Postgres DB上插入数据,如下所示:

  

http://123.123.10.10/checkin?userid=clive&token=1234jhhasdbn

package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    _ "github.com/lib/pq"
)

const (
    host     = "localhost"
    port     = 2019
    user     = "postgres"
    password = "dbadmin"
    dbname   = "oc-indo-dev"
)


type Response struct {
    Status  int    `json:"status"`
    Message string `json:"message"`
    Token string `json:"token"`
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/checkin", checkin).Methods("POST")
    http.Handle("/", router)
    fmt.Println("Connected to port 1234")
    log.Fatal(http.ListenAndServe(":1234", router))
}

func DBconnect() *sql.DB {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)
    db, err := sql.Open("postgres", psqlInfo)

    if err != nil {
        log.Fatal(err)
    }

    return db
}

func checkin(w http.ResponseWriter, r *http.Request) {
    var response Response
    var tmpToken string

    r.ParseForm()
    userId := r.Form.Get("userid")
    userToken := r.Form.Get("token")

    db := DBconnect()
    defer db.Close()

    query := `INSERT INTO oc_token (userid, time, token) VALUES ($1, $2, $3) RETURNING token`
    err = db.QueryRow(query, userId, time.Now(), userToken).Scan(&tmpToken)

    if (err != nil){
        response.Status = 500
        response.Message = "Invalid checkin"
        response.Token = ""
    } else {
        response.Status = 200
        response.Message = "Succesfully checkedin"
        response.Token = tmpToken
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(response)

}

Go编译器(我正在使用v1.13)抱怨:

  

。\ checkin.go:63:2:未定义:错误

     

。\ checkin.go:65:6:undefined:err

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

在签入中,您没有声明err变量。

使用:

var err error

或:=速记

err := db.QueryRow(query, userId, time.Now(), userToken).Scan(&tmpToken)