Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

go

go-gin

So i have a struct :

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

When i return my object with gin and :

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 me :

null

instead of

[]

How to return an empty array ?

Regards

like image 797
Bussiere Avatar asked May 18 '19 16:05

Bussiere


People also ask

How do I return an empty slice in Golang?

The zero value of a Slice is nil, so in our example above, when we declare var foo []string the value of foo is actually nil not an empty slice of string [] . Empty slice can be generated by using Short Variable Declarations eg. foo := []string{} or make function.

Is array empty Golang?

To check if the array is empty follow these steps: Check with the builtin len() function, for example, len(slice) <= 0 . If the array is empty, skip the for a loop.

What is Gin H?

gin. H is defined as type H map[string]interface{} . You can index it just like a map. In your code, msg is an interface{} whose dynamic type is gin.H , as seen from the output of reflect.TypeOf , so you can't index it directly.


1 Answers

So the solution was to initialize it with :

productConstructed.BrandMedals = make([]string, 0)
like image 121
Bussiere Avatar answered Sep 30 '22 15:09

Bussiere