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
119 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.Readerwith aClose()method.An advantage of
io.Readeroverstringand[]byteis 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/httpfunctions to a[]byte:Use the function like this: