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
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.
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.
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.
So the solution was to initialize it with :
productConstructed.BrandMedals = make([]string, 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With