I have a table in a Postgres db (artwork_migrate_era)
I'm using GORM. I find that in order for my model to work with an already existing table, I need to use the TableName() method like so:
type Era struct {
id int `json:"id"`
era_name string `json:"era_name"`
last_modified time.Time `json:"last_modified"`
}
// allows to use gorm model with already-existing table in db: https://stackoverflow.com/questions/66318666/golang-gorm-how-to-create-a-model-for-an-existing-table
func (Era) TableName() string {
return "artwork_migrate_era"
}
I'm also using GIN to make requests:
func main() {
dsn := "...db_credentials..."
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect to db")
}
db.AutoMigrate(&Era{})
router := gin.Default()
router.GET("/era/:id", func(c *gin.Context) {
id := c.Param("id")
var era Era
db.Where("id = ?", id).Find(&era)
c.JSON(http.StatusOK, gin.H{
"Era": era.era_name,
})
})
router.Run("localhost:8080")
}
when I make the following request: curl localhost:8080/era/4
I get get the following response: {"Era":""}
Am I just missing something obvious?
db.Where("id = ?", id).Find(&era)
would not be able to map the data to your struct export all the members of your struct by making the first letter Capital