package httpclient import ( "errors" "fmt" "io" "net/http" ) // ErrResponseTooLarge means the complete decoded HTTP response exceeded its budget. var ErrResponseTooLarge = errors.New("httpclient: response body exceeds limit") // ReadResponseBody reads a complete bounded body, including one extra byte to // distinguish an exact limit from truncation. Standard Transport gzip decoding // occurs before this reader, so the limit covers decompressed data as well. func ReadResponseBody(resp *http.Response, limit int64) ([]byte, error) { if limit <= 0 || limit == int64(^uint64(0)>>1) { return nil, fmt.Errorf("httpclient: invalid response limit") } if resp.ContentLength > limit { return nil, ErrResponseTooLarge } body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) if err != nil { return nil, err } if int64(len(body)) > limit { return nil, ErrResponseTooLarge } return body, nil }