readBody function

Future<Result<Uint8List, Rejection>> readBody(
  1. Request request, {
  2. int limit = defaultBodyLimit,
})

Reads the whole request body, rejecting with 413 past limit.

content-length is checked first so an oversized upload is refused before it is read. A body arriving without one — chunked, which the client chooses — is counted as it flows, because a declared length is a claim.

The effective limit is the stricter of limit and any limit configured on the router. See effectiveBodyLimit.

Implementation

Future<Result<Uint8List, Rejection>> readBody(
  Request request, {
  int limit = defaultBodyLimit,
}) async {
  final effective = effectiveBodyLimit(request, limit);

  Rejection tooLarge() =>
      Rejection.payloadTooLarge('body exceeds $effective bytes');

  final declared = RequestParts.of(request).contentLength;
  if (declared != null && declared > effective) return Err(tooLarge());

  final builder = BytesBuilder(copy: false);
  await for (final chunk in request.read()) {
    builder.add(chunk);
    if (builder.length > effective) return Err(tooLarge());
  }
  return Ok(builder.takeBytes());
}