Gorm – Not fetching data

I am trying to setup a REST API using Gin and Gorm. Following is my main.go:

package main

import (
    "app/config"
    "app/service"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    // Connect to database
    config.ConnectDatabase()
    r.GET("/books", service.FindBooks)
    // Run the server
    r.Run()
}

And in my config/setup.go, I am trying to connect to DB like so

package config

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

var DB *gorm.DB

// ConnectDatabase : Setup connection to database
func ConnectDatabase() {
    database, err := gorm.Open("mysql", "root:[email protected](127.0.0.1:3306)/test_db")
    database.SingularTable(true)
    if err != nil {
        panic("Failed to connect to database!")
    }
    DB = database
}

In my service/book.go, I have the following logic:

package service

import (
    "errors"
    "app/config"
    "app/model"
    "fmt"
    "net/http"
    "github.com/gin-gonic/gin"
)

// FindBooks : Get all books
func FindBooks(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"data": FindAllBooks()})
}

// FindAllBooks : Fetch all book from DB
func FindAllBooks() []model.Book {
    var book []model.Book
    config.DB.Find(&book)
    for i := 0; i < len(book); i++ {
        fmt.Println(book[i])
    }
    return book
}

And my model/Book.go is defined as follows:

package model

type Book struct {
    id        int64  `json:"id" gorm:"primary_key"`
    label     string `json:"label" gorm:"type:varchar(255)"`
}

When I run the application using go run main.go, following is the log I can see:

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /books                    --> feedconsumer/service.FindBooks (3 handlers)
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
{0   }
[GIN] 2021/03/09 - 12:43:43 | 200 |    2.313864ms |             ::1 | GET      "/books"

Basically, the {0 } means the object is not fetched actually. What am I missing here?

Answer

GORM uses snake_case for defining field of models. Link to docs

So for your case, it is basically:

package model

type Book struct {
    ID        int64  `json:"id" gorm:"primary_key"`
    Label     string `json:"label" gorm:"type:varchar(255)"`
}

Leave a Reply

Your email address will not be published. Required fields are marked *