0

I started Go very recently and decided to create a simple CRUD back-end using gorm and gin.I have implemented the following function to retrieve a query result.

I can't get some of the endpoints to work.

func GetCurrentStock(c *gin.Context) {
    result := initializers.DB.Table("dev.inventory_live").Debug().Select("sum(qtynos)").Where("NOT is_cut AND (remarks IS NULL OR remarks = '')")

    c.JSON(http.StatusOK, gin.H{
        "result": result,
    })
}

When I send a request to the end point, I keep getting this error

Error #01: json: unsupported type: func() time.Time

Is there something I am missing? I haven't been able to find a solution

fuzzy-memory
  • 157
  • 8
  • 3
    `result` is of type `*gorm.DB` which embeds `*gorm.Config` which has a field [`NowFunc func() time.Time`](https://pkg.go.dev/gorm.io/gorm#Config.NowFunc). Passing `result` to `c.JSON` will attempt to marshal it as JSON. __Functions cannot be marshaled into JSON__, hence the error. Neither are you supposed to be marshaling `*gorm.DB`. In other words, `result` is not what you think it is. Read the [docs](https://pkg.go.dev/gorm.io/gorm), read the official tutorials from [gorm.io](https://gorm.io/docs/). – mkopriva Feb 25 '23 at 15:09

1 Answers1

1

Using the input @mkopriva gave and another question I found, I realised I was incorrectly retrieving the result. The right way is:

func GetCurrentStock(c *gin.Context) {
    var result int
    initializers.DB.Table("dev.inventory_live").Select(fmt.Sprintf("sum(%v)", dim)).Where("NOT is_cut AND (remarks IS NULL OR remarks = '')").Scan(&result)

    c.JSON(http.StatusOK, gin.H{
        "result": result,
    })
}
fuzzy-memory
  • 157
  • 8