The "net/http" golang package has a response type which I find confusing. It defines a member Body io.ReadCloser
which requires an additional call to some form of an io writer to process. Why did the developers not choose to make the Body a []bytes
or a string
? These seem like much more obvious, natural choices to me.
Golang HTTP Request types
92 views Asked by EnnFour At
1
An HTTP response body is a stream of bytes on the network connection. The io.Reader type is Go's representation of a stream of bytes. The Response.Body field is typed as io.ReadCloser which is an
io.Reader
with aClose()
method.An advantage of
io.Reader
overstring
and[]byte
is that the application can stream through the response without loading the entire response in memory.Use io.ReadAll to read the io.Reader's data to a []byte.
Here's a convenient helper function converting the
(*http.Response, error)
return values from thenet/http
functions to a[]byte
:Use the function like this: