writeResponse function

Future<void> writeResponse(
  1. HttpRequest request,
  2. Future<Response> resp
)

writeResponse takes in an HTTP request and a steward response, and writes the contents of the steward response to the HTTP response. TODO: this should only be called by Steward

Implementation

Future<void> writeResponse(HttpRequest request, Future<Response> resp) async {
  // if we dont know what the content type is at this point, we infer it.
  var response = await resp;
  var body = await response.body;
  var jsonBody = body;
  try {
    jsonBody = jsonEncode(body);
  } catch (_) {
    // TODO: should we warn the user that this failed?
  }
  var bodyIsJsonable = jsonBody != body;

  if (response.headers.contentType == null) {
    if (bodyIsJsonable && body is! String) {
      response.headers.contentType = ContentType.json;
    } else {
      response.headers.contentType = ContentType.text;
    }
  }

  // If this _SHOULD_ be JSON and the body can be converted to JSON, do it!
  if (response.headers.contentType == ContentType.json &&
      bodyIsJsonable &&
      !(body is int || body is double || body is String || body == null)) {
    body = jsonBody;
  }

  request.response.headers.contentType = response.headers.contentType;
  request.response.headers.date = response.headers.date;

  if (response.headers[_headersKey] != null) {
    request.response.headers.set(_headersKey, response.headers[_headersKey]!);
  }

  if (response.headers[_originKey] != null) {
    request.response.headers.set(_originKey, response.headers[_originKey]!);
  }

  if (response.headers[_methodsKey] != null) {
    request.response.headers.set(_methodsKey, response.headers[_methodsKey]!);
  }

  request.response.statusCode = response.statusCode;
  request.response.write(body);

  return;
}