The function returns nil

I’m a beginner, I wrote a function that checks if in the request pagination.Main == true , then the function returns prod, otherwise prod_2. The default parameter is main == true , but if I change it to false I get "data": null

My funcs:

func GetAllIproducts(q *models.Products, g *models.Products_2, pagination *models.Params) (*[]models.Products, *[]models.Products_2) {
    var prod []models.Products
    var prod_2 []models.Products_2
    offset := (pagination.Page - 1) * pagination.Limit
    if pagination.Main {
        if pagination.Cat_id == nil {
            config.DB.Model(&models.Products{}).Where(q).Limit(pagination.Limit).Offset(offset).Find(&prod)
        } else {
            config.DB.Model(&models.Products{}).Where(q).Where("cat_id IN (?)", pagination.Cat_id).Limit(pagination.Limit).Offset(offset).Find(&prod)
        }
        return &prod, nil
    } else {
        if pagination.Cat_id == nil {
            config.DB.Model(&models.Products_2{}).Where(g).Limit(pagination.Limit).Offset(offset).Find(&prod_2)
        } else {
            config.DB.Model(&models.Products_2{}).Where(g).Where("cat_id IN (?)", pagination.Cat_id).Limit(pagination.Limit).Offset(offset).Find(&prod_2)
        }
        return nil, &prod_2
    }
}
func GetAllProducts_by_multi_params(c *gin.Context) {
    pagination := GenerateMultiParams(c)
    var prod models.Products
    var prod_2 models.Products_2
    ProdLists, _ := GetAllIproducts(&prod, &prod_2, &pagination)
    c.JSON(http.StatusOK, gin.H{
        "data": ProdLists,
    })
}

>Solution :

The second return value is hold by the underscore _ in

ProdLists, _ := GetAllIproducts(&prod, &prod_2, &pagination)

You can change it to Prod2Lists and check for nil, like:

ProdLists, Prod2Lists := GetAllIproducts(&prod, &prod_2, &pagination)
If ProdLists != nil {
    c.JSON(http.StatusOK, gin.H{
        "data": ProdLists,
    })
} else {
    c.JSON(http.StatusOK, gin.H{
        "data": Prod2Lists,
})}

Leave a Reply