0

I'm using http module. The Front-End developers team asking me when there are no results, send a response with an empty list and status code 204. I tried this:

AllPosts  := logic.MergedSearchSearchPost(params)

if len(AllPosts.Posts) == 0 {
    w.WriteHeader(http.StatusNoContent)
    json.NewEncoder(w).Encode(AllPosts)
}

And in this case, AllPosts is something like this:

{
    "total": 0,
    "is_finished": true,
    "query_id": "c2x86XSZaU",
    "posts": null
}

The problem is that I can not send anything after setting the status code to 204. So the response is null. I want to send AllPosts above with the 204 status code. Is there any way?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
mrasoolmirza
  • 787
  • 1
  • 6
  • 22
  • 6
    `204 No Content` response can't contain any content in the body by definition: https://tools.ietf.org/html/rfc7231#section-6.3.5 – MarcoLucidi Feb 21 '21 at 09:38
  • 2
    204 seems wrong for this API. This seems like it should be a 200 with an empty list as the body. – Adam Smith Feb 21 '21 at 09:41

1 Answers1

3

The Front-End developers team asking me when there are no results, send a response with an empty list and status code 204

These 2 contradicts each other. Empty list is some content. This directly breach HTTP standard:

A 204 response is terminated by the first empty line after the header fields because it cannot contain a message body.

Go HTTP library is just not allowing you to do so.

Community
  • 1
  • 1
rkosegi
  • 14,165
  • 5
  • 50
  • 83