I want to discard all bytes over a given limit during reading of HTTP Response (skip too large response) using LimitedReader.
Is this the correct way to do that?
func getRequestData(req *http.Request, client *http.Client,
responseSizeLimit int64) ([]byte, error) {
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer func() {
io.Copy(ioutil.Discard, resp.Body) // response body must be read to the end and closed
resp.Body.Close()
}()
buffer := bufio.NewReader(resp.Body)
reader := io.LimitReader(buffer, responseSizeLimit)
return ioutil.ReadAll(reader)
}
And what if I want to return io.Reader
instead of []byte
, is it possible for http.Response.Body
and limitedReader
?