Elliot Reeve
Elliot Reeve

Reputation: 941

Empty Struct on Response

I have a query which casts into a struct. But when the query returns no results the response is null - how do I get this to be an empty array []?

_, err := dbmap.Select(&response.DevTeam, "SELECT * FROM DevTeam WHERE app_id = ? LIMIT ? OFFSET ?", a_id, limit, offset)

Response when no results:

{
  "data": null,
  "meta": "success"
}

Desired response when no results:

{
  "data": [],
  "meta": "success"
}

Still getting null - my struct setup is:

type HttpResonse struct {
    DevTeam []DevTeam `json:"data"`
}

I am using response.DevTeam = []models.DevTeam{} as suggested below but still getting null.

Response section:

s.Count = int64(len(response.DevTeam))  
c.JSON(httpcode, gin.H{"meta": s, "data": response.DevTeam})

Upvotes: 0

Views: 1321

Answers (1)

icza
icza

Reputation: 418137

A value of slice type being nil encodes as the null JSON object. A non-nil empty slice is marshaled into an empty array [].

Before marshaling response, check the DevTeam field, and if it's nil, explicitly set a slice value with 0 length, e.g.:

if response.DevTeam == nil {
   response.DevTeam = []models.DevTeam{} 
}

Or alternatively when you create your gin.H wrapper, use an empty slice instead of response.DevTeam if the latter equals to nil.

See this simple example:

type Pt struct {
    DevTeam []string
}

p := Pt{}
json.NewEncoder(os.Stdout).Encode(p)

p.DevTeam = []string{}
json.NewEncoder(os.Stdout).Encode(p)

Output (try it on the Go Playground):

{"DevTeam":null}
{"DevTeam":[]}

Upvotes: 1

Related Questions