DB contents are retrieved using Find in GORM, but all are empty

Asked 1 years ago, Updated 1 years ago, 79 views

I am currently making a simple API using GAE+CloudSQL.
We tried to implement an API that could retrieve all DB data and created the following code:

package main

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

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

vardb*gorm.DB

funcmain(){
    db = DB()

    http.HandleFunc("/user", func(whttp.ResponseWriter,r*http.Request){
        prefer db.Close()
        var people [ ] Person
        db.Find (&people)
        str,_: = json.Marshal(people)
        fmt.Printf("%s\n", 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))
}

US>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
}

However, if you implement this and hit the API, nothing will be printed.
After investigating the cause,
db.Find(&people)
After the people in , the number of elements in the array matched the number of data in the DB, but the contents were all empty or zero.

I have no idea if there is a problem with the implementation or GCP configuration.
Please tell me the solution.Thank you for your cooperation.

go google-app-engine gorm

2022-09-30 14:22

2 Answers

Sorry, I made a simple mistake.

http.HandleFunc("/user", func(whttp.ResponseWriter,r*http.Request){
    prefer db.Close()
    ~~~~
})

As it was written, the DB connection will be lost after this function is executed.
Correct the code and write db.Close() directly below the main statement.
I was able to get both person.Name and person.Age.


2022-09-30 14:22

Person to

`gorm:"column:name"`

Since there is no column name specified in the format , you cannot map rows retrieved from the database to a structure, and all elements appear to be empty. What do you think?

https://gorm.io/docs/models.html


2022-09-30 14:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.