0

I have a function that returns a product by its ID, but the problem is that it does not return it as a data array

func GetProductsById(c *gin.Context) {
    var Product models.Products
    if err := config.DB.Where("id=?", c.Query("prod_id")).First(&Product).Error; err != nil {
        c.JSON(http.StatusInternalServerError, err.Error())
    } else {
        c.JSON(http.StatusOK, gin.H{"data": &Product})
    }
}

json response

{
    "data": {
        "ID": 1,
        ...
        "Feedback": null
    }
}

I want this:

{
    "data": [{
        "ID": 1,
        ...
        "Feedback": null
    }]
}
1
  • 1
    gin.H{"data": []models.Products{Product}}. If you're on Go1.18+ you can also do gin.H{"data": []any{Product}}. Commented Jul 16, 2022 at 9:18

1 Answer 1

2

As suggested by @mkopriva, to easily return a struct as a single-element JSON array, wrap it in a slice literal.

var p models.Product
// ...
c.JSON(http.StatusOK, gin.H{"data": []models.Product{p}})

If you don't want to specify a particular type for the slice items, you can use []interface{}, or []any starting from Go 1.18

c.JSON(http.StatusOK, gin.H{"data": []interface{}{p}})
// c.JSON(http.StatusOK, gin.H{"data": []any{p}})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.