Tobias Contreras <
tobi...@gmail.com>
writes:
> body, err := ioutil.ReadAll(r.Body)
If you'll please forgive me, I'm on a bit of a crusade against
ioutil.ReadAll -- I see it used all over the place unnecessarily and
often in harmful ways.
It requires a contiguous allocation of memory to hold whatever happens
to be on the other end of that io.Reader.
In *most* cases where I see people doing this, they want to do
something incremental with it when they're done (such as save it to a
file or run it through a parser).
e.g. here, you are just trying to parse JSON, which you can do just fine
with an io.Reader.
> var statements []Statement //but what if json is a single statement
> err = json.Unmarshal([]byte(body), &statements)
Instead of this, you can just use a json.Decoder and parse on the fly:
d := json.NewDecoder(r.Body)
err = d.Decode(&statements)
The same pattern works the same way with an infinite multi-object JSON
stream or a single small object.
In your particular case, it may not make a practical difference, but,
IMO, it's good to think in terms of Readers and Writers vs. large slabs
of contiguous memory.
--
dustin