You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I propose a new, simple, but very useful method for net/http/httputil:
funcReadBody(res*http.Response) ([]byte, error) {
// A ContentLength value of -1 indicates that the length is unknown.ifres.ContentLength==-1 {
// Fall back to ReadAll.returnioutil.ReadAll(res.Body)
} else {
body:=make([]byte, res.ContentLength)
// No need to check the number of bytes read as err will// be != nil if it's less than ContentLength._, err:=io.ReadFull(res.Body, body)
returnbody, err
}
}
Usually people use ioutil.ReadAll to read the body of an http response. This will result in at least one garbaged bytes.Buffer and some over allocating of the resulting []byte. This new method is similar to ioutil.ReadAll only it uses the ContentLength to only allocate the number of bytes really needed.
The text was updated successfully, but these errors were encountered:
I guess it should be two separate methods such as ReadRequestBody and ReadResponseBody. Or just one method with an interface{} as argument but I don't think that's something done much in the standard library.
I don't like the idea of encouraging more ReadAll-sorts of interfaces, especially here where the ContentLength isn't under your control or even known.
Also, this doesn't respect StatusCode as an error.
I do like the idea of reducing some of the boilerplate associated with HTTP, but I don't think this is the answer. I want to see something which lets people declare limits (perhaps with a sane default if undeclared) and also lets them respect HTTP status codes as well.
Also, it should be a method on Response or Client, not a top-level function.
I propose a new, simple, but very useful method for
net/http/httputil
:Usually people use
ioutil.ReadAll
to read the body of an http response. This will result in at least one garbagedbytes.Buffer
and some over allocating of the resulting[]byte
. This new method is similar toioutil.ReadAll
only it uses theContentLength
to only allocate the number of bytes really needed.The text was updated successfully, but these errors were encountered: