简体   繁体   中英

Golang (GIN Framework) : GORM Query didnt work

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

If your code has database connection error try to add some logger. I usually use logrus logger:

newLogger := logger.New(
    config.Log,
    logger.Config{
        SlowThreshold: time.Second,
        LogLevel:      logger.Error,
        Colorful:      false,
    },
)

and configure logger with gorm connection line

database, err := gorm.Open("root:root@/insp?charset=utf8&parseTime=True&loc=Local", &gorm.Config{Logger: newLogger})

On production version I recommended use Error log level, but in debug mode you can use Info log level to see SQL queries to db.

And I think I am using newer version than Question author. Sorry if that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM