Skip to content

Commit

Permalink
net/http: add MaxBytesError
Browse files Browse the repository at this point in the history
  • Loading branch information
earthboundkid committed Mar 28, 2022
1 parent 0652274 commit 06110fb
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/net/http/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -1124,7 +1124,7 @@ func readRequest(b *bufio.Reader) (req *Request, err error) {
// MaxBytesReader is similar to io.LimitReader but is intended for
// limiting the size of incoming request bodies. In contrast to
// io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a
// non-EOF error for a Read beyond the limit, and closes the
// MaxBytesError for a Read beyond the limit, and closes the
// underlying reader when its Close method is called.
//
// MaxBytesReader prevents clients from accidentally or maliciously
Expand All @@ -1133,12 +1133,23 @@ func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser {
if n < 0 { // Treat negative limits as equivalent to 0.
n = 0
}
return &maxBytesReader{w: w, r: r, n: n}
return &maxBytesReader{w: w, r: r, i: n, n: n}
}

// MaxBytesError is returned by MaxBytesReader when its read limit is exceeded.
type MaxBytesError struct {
Limit int64
}

func (e MaxBytesError) Error() string {
// Due to Hyrum's law, this text cannot be changed.
return "http: request body too large"
}

type maxBytesReader struct {
w ResponseWriter
r io.ReadCloser // underlying reader
i int64 // max bytes initially, for MaxBytesError
n int64 // max bytes remaining
err error // sticky error
}
Expand Down Expand Up @@ -1180,7 +1191,7 @@ func (l *maxBytesReader) Read(p []byte) (n int, err error) {
if res, ok := l.w.(requestTooLarger); ok {
res.requestTooLarge()
}
l.err = errors.New("http: request body too large")
l.err = MaxBytesError{l.i}
return n, l.err
}

Expand Down
7 changes: 7 additions & 0 deletions src/net/http/serve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3035,6 +3035,13 @@ func testRequestBodyLimit(t *testing.T, h2 bool) {
if n != limit {
t.Errorf("io.Copy = %d, want %d", n, limit)
}
mb, ok := err.(MaxBytesError)
if !ok {
t.Errorf("expected MaxBytesError, got %T", err)
}
if mb.Limit != limit {
t.Errorf("MaxBytesError.Limit = %d, want %d", mb.Limit, limit)
}
}))
defer cst.close()

Expand Down

0 comments on commit 06110fb

Please sign in to comment.