0

我正在尝试实现一个简单的 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

如何解决这个问题?

4

1 回答 1

2

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

使用:

var err error

或 := 速记

err := db.QueryRow(query, userId, time.Now(), userToken).Scan(&tmpToken)
于 2019-09-17T10:24:13.523 回答