Sorry for asking such a dumb question. I just learn golang several days ago.
And I want to build API Services with GIN Framework. I use Jinzhu gorm for query mysql database.
The problem is, my query result always null.
This is my code:
Model folder:
package models
import "github.com/jinzhu/gorm"
type (
User struct {
gorm.Model
Name string `json:"name"`
Phone string `json:"phone"`
Address string `json:"address"`
Age int `json:"age"`
Gender string `json:"gender"`
}
)
Resource folder:
package resources
import (
// Standard library packages
"net/http"
// Third party packages
"../models"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
)
type (
UserResource struct {
db *gorm.DB
}
)
func NewUserResource(s *gorm.DB) *UserResource {
return &UserResource{s}
}
func (ur UserResource) Index(c *gin.Context) {
var users []models.User
ur.db.Find(&users)
if len(users) <= 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.StatusNotFound, "error": "not found"})
return
}
c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "data": users})
}
And the last is controller folder:
package controllers
import (
"../resources"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type UserService struct {
}
func Database() *gorm.DB {
//open a db connection
db, err := gorm.Open("mysql", "root:root@/insp?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic("failed to connect database")
}
return db
}
func (s *UserService) Run() {
// Instantiate a new router
router := gin.Default()
v1 := router.Group("/api/v1/users")
{
db := Database()
us := resources.NewUserResource(db)
v1.GET("/", us.Index)
}
router.Run(":9090")
}
everytime I hit the endpoint to get list of users, the result always return user not found.
But When I change into Raw query, it works well
ur.db.Raw("SELECT * FROM users").Scan(&users)
I already try to read the GORM docs.
anyone know how to fix it?
Thanks for advice
gorm
error.err := ur.db.Find(&users).Error
– Bogdan Iulian Bursucgorm
is trying to create as SQL:ur.db.Debug().Find(&users)
– Bogdan Iulian Bursuc