respond method

Future respond(
  1. Response conduitResponse
)

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 conduitResponse are added to the HTTP response. If conduitResponse has a Response.body, this request will attempt to encode the body data according to the Content-Type in the conduitResponse's Response.headers.

Implementation

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

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

  final _Reference<String> compressionType = _Reference(null);
  var body = conduitResponse.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(conduitResponse, compressionType);
  }

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

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

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

  response.headers.add(
    HttpHeaders.contentTypeHeader,
    conduitResponse.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(conduitResponse, compressionType);
    if (compressionType.value != null) {
      response.headers
          .add(HttpHeaders.contentEncodingHeader, compressionType.value!);
    }
    response.headers.add(HttpHeaders.transferEncodingHeader, "chunked");
    response.bufferOutput = conduitResponse.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.");
}