To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CANODV3%3DpXGcHzhSmaLr3f911i2CCYb0_j8CGH7zKAZXd_xTD-A%40mail.gmail.com.
I always use `json.NewDecoder(r.Body).Decode(&payload)`
The code is more succinct than reading the entire body into a buffer, and then unmarshalling it. And there is only one error to check.
If I was super concerned about people sending trailing gibberish to my server, I could call `dec.Buffered()` to see
if there was anything left after the json object. I generally have not seen people sending garbage after their requests.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/e9a6f76d-17bb-40da-84b3-2b1b8d0f3b35n%40googlegroups.com.
How do you know, if you don't check? FTR, it's not just about sending garbage, it's also about requests accidentally being truncated or just generally garbled.
json.NewDecoder(r.Body).Decode(&payload) will return an error if the request is garbled or truncated.
The other nice thing about this code is that it composes nicely with the context.
net/http provides the body as a Reader. And json NewDecoder takes a reader. The two fit together nicely, without any need
for adapters.
The API looks like it should be able to decode a large payload without allocating a large buffer to hold the bytes.
Sadly this is not the way encoding/json is implemented.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9af4c4a2-0267-4ed7-9bf0-7cc7afd4029en%40googlegroups.com.