douju6651 2019-07-11 23:46
浏览 51

查找方法以获取数据库中返回空数据集的记录

Now, I try to make an API with using GAE+CloudSQL. I made this code.

package main

import (
    "encoding/json"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
    "log"
    "net/http"
    "os"
)

type Person struct {
    gorm.Model
    Name string `json:"name"`
    Age  int    `json:"age"`
}

var db *gorm.DB

func main() {
    db = DB()

    http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
        defer db.Close()
        var people []Person
        db.Find(&people)
        str, _ := json.Marshal(people)
        fmt.Printf("%s
", str)
        return
    })

    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
        log.Printf("Defaulting to port %s", port)
    }

    log.Printf("Listening on port %s", port)
    log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}

func DB() *gorm.DB {
    var (
        connectionName = os.Getenv("CLOUDSQL_CONNECTION_NAME")
        user           = os.Getenv("CLOUDSQL_USER")
        password       = os.Getenv("CLOUDSQL_PASSWORD")
        socket         = os.Getenv("CLOUDSQL_SOCKET_PREFIX")
        databaseName   = os.Getenv("CLOUDSQL_DATABASE_NAME")
        option         = os.Getenv("CLOUDSQL_OPTION")
    )

    if socket == "" {
        socket = "/cloudsql"
    }
    if option == "" {
        option = "?parseTime=true"
    }

    dbURI := fmt.Sprintf("%s:%s@unix(%s/%s)/%s%s", user, password, socket, connectionName, databaseName, option)
    conn, err := gorm.Open("mysql", dbURI)
    if err != nil {
        panic(fmt.Sprintf("DB: %v", err))
    }

    return conn
}

With the help of cloud I can get people data.

people.length is equal to the number of DB datas.

But, what I am getting is

person.Name is "" and person.Age = 0.

I cannot understand why I could not get any data. Please tell me how to fix this issue.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度