danielgtaylor / huma

Huma REST/HTTP API Framework for Golang with OpenAPI 3.1
https://huma.rocks/
MIT License
1.71k stars 134 forks source link

empty array will be send out as null #457

Closed ScriptType closed 1 week ago

ScriptType commented 1 month ago

i have following type which im returning. type InstanceArrayResponse struct { Body []*InstanceBody }

if the Body is now an empty array i get null as a response when testing the api.

fmt.Println(instancesResponse) //&{[]}

so &{[]} is what i`m returning in the handler but in the frontend i receive null :/

When the array is Filled with values its working as expected.

danielgtaylor commented 1 month ago

@ScriptType this is how the Golang JSON encoder works:

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

From https://pkg.go.dev/encoding/json#Marshal

What should the default behavior be? Should it be to send no body, null, or [] / {} when the body is nil or empty?

bshtmichielsen commented 1 month ago

Hi both I experienced a similar situation and was a little surprised too. I would have expected that if Body == nil it outputs null, however when Body contains an empty slice, I would have expected [] as output.

ScriptType commented 1 week ago

@ScriptType this is how the Golang JSON encoder works:

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

From https://pkg.go.dev/encoding/json#Marshal

What should the default behavior be? Should it be to send no body, null, or [] / {} when the body is nil or empty?

Yep You are right didn't read the docs well enough, my bad.(and im pretty new to go) Thought it was a Huma thing as i couldn't think of it to be the "default" way.

It still Suprises me to be honest :P.

But yea not a Hma problem so closed