-1

我正在尝试开发一个 API 接口来访问包含 34,000 多个条目的数据库。我正在使用 go 并在我已将 csv 文件导入到的 sqlite3 数据库上绘图。数据库的结构是:

"ID" TEXT,
"title" TEXT,
"description" TEXT,
"streetaddress" TEXT,
"city" TEXT,
"state" TEXT,
"amenityfeatures" TEXT,
"locationtype" TEXT,
"Year" TEXT,
"notes" TEXT,
"lon" INTEGER,
"lat" INTEGER,
"status" TEXT

这是我用来构建响应的代码: 在 person.go 中:

    package models

import (
    "database/sql"
    "strconv"
    _ "github.com/mattn/go-sqlite3"
)

var DB *sql.DB

func ConnectDatabase() error {
    db, err := sql.Open("sqlite3", "./mgg.db")
    if err != nil {
        return err
    }

    DB = db
    return nil
}

type Person struct {
    ID string `json:"id"`
    lon float64 `json:"lon"`
    lat float64 `json:"lat"`
    status string `json:"status"`
    Year  int `json:"Year"`
}

func GetPersons(count int) ([]Person, error) {

    rows, err := DB.Query("SELECT ID, lon, lat, status, Year from mgg LIMIT " + strconv.Itoa(count))

    if err != nil {
        return nil, err
    }

    defer rows.Close()

    people := make([]Person, 0)

    for rows.Next() {
        singlePerson := Person{}
        err = rows.Scan(&singlePerson.ID, &singlePerson.lon, &singlePerson.lat, &singlePerson.status, &singlePerson.Year)

        if err != nil {
            return nil, err
        }

        people = append(people, singlePerson)
    }

    err = rows.Err()

    if err != nil {
        return nil, err
    }

    return people, err
}

然后在 main.go 中:

package main

import (
    "PersonWeb/models"
    //"fmt"
    "log"
    "net/http"
    //"strconv"
    "github.com/gin-gonic/gin"
)

func main() {

    err := models.ConnectDatabase()
    checkErr(err)

    r := gin.Default()

    // API v1
    v1 := r.Group("/api/v1")
    {
        v1.GET("person", getPersons)
        // v1.GET("person/:id", getPersonById)
        // v1.POST("person", addPerson)
        // v1.PUT("person/:id", updatePerson)
        // v1.DELETE("person/:id", deletePerson)
        // v1.OPTIONS("person", options)
    }

    // By default it serves on :8080 unless a
    // PORT environment variable was defined.
    r.Run()
}

func getPersons(c *gin.Context) {

    persons, err := models.GetPersons(100)

    checkErr(err)

    if persons == nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "No Records Found"})
        return
    } else {
        c.JSON(http.StatusOK, gin.H{"data": persons})
    }
}

api 响应(我只包括一部分)返回:

        {
            "id": "DE039",
            "Year": 1980
        },

我确定我遗漏了一些明显的东西。有谁知道为什么会出现 id 和 Year 而不是任何其他值?

4

0 回答 0