respond method

Future respond(
  1. Response aquedartResponse
)

Sends a Response to this Request's client.

Do not invoke this method directly.

Controllers invoke this method to respond to this request.

Once this method has executed, the Request is no longer valid. All headers from aquedartResponse are added to the HTTP response. If aquedartResponse has a Response.body, this request will attempt to encode the body data according to the Content-Type in the aquedartResponse's Response.headers.

Implementation

Future respond(Response aquedartResponse) {
  respondDate = DateTime.now().toUtc();

  final modifiers = _responseModifiers;
  _responseModifiers = null;
  modifiers?.forEach((modifier) {
    modifier(aquedartResponse);
  });

  _Reference<String?> compressionType = _Reference(null);
  var body = aquedartResponse.body;
  if (body is! Stream) {
    // Note: this pre-encodes the body in memory, such that encoding fails this will throw and we can return a 500
    // because we have yet to write to the response.
    body = _responseBodyBytes(aquedartResponse, compressionType);
  }

  response.statusCode = aquedartResponse.statusCode!;
  aquedartResponse.headers.forEach((k, v) {
    response.headers.add(k, v as Object);
  });

  if (aquedartResponse.cachePolicy != null) {
    response.headers.add(HttpHeaders.cacheControlHeader,
        aquedartResponse.cachePolicy!.headerValue);
  }

  if (body == null) {
    response.headers.removeAll(HttpHeaders.contentTypeHeader);
    return response.close();
  }

  response.headers.add(
      HttpHeaders.contentTypeHeader, aquedartResponse.contentType.toString());

  if (body is List<int>) {
    if (compressionType.value != null) {
      response.headers
          .add(HttpHeaders.contentEncodingHeader, compressionType.value!);
    }
    response.headers.add(HttpHeaders.contentLengthHeader, body.length);

    response.add(body);

    return response.close();
  } else if (body is Stream) {
    // Otherwise, body is stream
    final bodyStream =
        _responseBodyStream(aquedartResponse, compressionType)!;
    if (compressionType.value != null) {
      response.headers
          .add(HttpHeaders.contentEncodingHeader, compressionType.value!);
    }
    response.headers.add(HttpHeaders.transferEncodingHeader, "chunked");
    response.bufferOutput = aquedartResponse.bufferOutput;

    return response.addStream(bodyStream).then((_) {
      return response.close();
    }).catchError((e, StackTrace st) {
      throw HTTPStreamingException(e, st);
    });
  }

  throw StateError("Invalid response body. Could not encode.");
}