Golang: Hack Empty response body

Sagar Bhatt
1 min readOct 14, 2019

--

Unmarshaling response in Go can be fatal when dealing with an empty response body.

e :=json.NewDecoder(response.Body).Decode(result)

In the above snippet response.Body is a type of *http.Response and result is an empty interface ( interface{} ). This code will look quite normal and can also do error handling.

But it will not work as expected when a response doesn’t have a body. In that case, variable e will have not nil value. Which is incorrect because the server can actually send an empty/null body in the response.

But thanks to Golang we have a quick-fix to fix this issue, just take a look at a below snippet.


err := json.NewDecoder(response.Body).Decode(result)
if err == io.EOF {
return nil
}
return err

And that is it.

--

--