Return ErrResponseTooLarge instead of truncating response body
WithMaxResponseBody wrapped the body in io.LimitedReader, which returns EOF at the cap, so Bytes/JSON/XML silently returned a truncated body with a nil error despite the documented contract. Read one byte past the limit and return the new ErrResponseTooLarge sentinel when exceeded; bodies exactly at the limit still succeed.
This commit is contained in:
@@ -2,6 +2,7 @@ package httpx_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -32,13 +33,30 @@ func TestClient_MaxResponseBody(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("truncates response exceeding limit", func(t *testing.T) {
|
||||
t.Run("returns ErrResponseTooLarge when exceeding limit", func(t *testing.T) {
|
||||
largeBody := strings.Repeat("x", 1000)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
fmt.Fprint(w, largeBody)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := httpx.New(httpx.WithMaxResponseBody(100))
|
||||
resp, err := client.Get(context.Background(), srv.URL+"/")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if _, err := resp.Bytes(); !errors.Is(err, httpx.ErrResponseTooLarge) {
|
||||
t.Fatalf("err = %v, want ErrResponseTooLarge", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allows body exactly at limit", func(t *testing.T) {
|
||||
exact := strings.Repeat("x", 100)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
fmt.Fprint(w, exact)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := httpx.New(httpx.WithMaxResponseBody(100))
|
||||
resp, err := client.Get(context.Background(), srv.URL+"/")
|
||||
if err != nil {
|
||||
@@ -46,7 +64,7 @@ func TestClient_MaxResponseBody(t *testing.T) {
|
||||
}
|
||||
b, err := resp.Bytes()
|
||||
if err != nil {
|
||||
t.Fatalf("reading body: %v", err)
|
||||
t.Fatalf("reading body at exact limit: %v", err)
|
||||
}
|
||||
if len(b) != 100 {
|
||||
t.Fatalf("body length = %d, want %d", len(b), 100)
|
||||
|
||||
Reference in New Issue
Block a user