jsongogo-gin

Return an empty array instead of null with golang for json return with gin


I have a struct:

type ProductConstructed struct {
    Name string `json:"Name"`
    BrandMedals []string `json:"BRAND_MEDALS"`
}

When I return my object with gin:

func  contructproduct(c *gin.Context) {
    var response ProductConstructed 
    response.Name = "toto"

    c.JSON(200, response)
}

func main() {
    var err error
    if err != nil {
        panic(err)
    }
    //gin.SetMode(gin.ReleaseMode)
    r := gin.Default()
    r.POST("/constructProductGo/v1/constructProduct", contructproduct)
    r.Run(":8200") // listen and serve on 0.0.0.0:8080
}

It returns:

null

instead of:

[]

How to return an empty array?


Solution

  • So the solution was to initialize it with :

    productConstructed.BrandMedals = make([]string, 0)