respond method

Future respond(
  1. Response liquidartResponse
)

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

Implementation

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

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

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

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

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

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

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