handleHttpRequest method

Future<void> handleHttpRequest(
  1. HttpRequest request
)
override

Implementation

Future<void> handleHttpRequest(HttpRequest request) async {
  var body = await request.toList();
  var uInt8List = mergeList(body);

  var _body;
  if (uInt8List.isEmpty) {
    _body = null;
  } else if (request.headers.contentType?.mimeType ==
      ContentType.json.mimeType) {
    try {
      _body = json.decode(utf8.decode(uInt8List));
    } on Exception {
      _body = null;
    }
  } else if (request.headers.contentType?.mimeType ==
          ContentType.html.mimeType ||
      request.headers.contentType == ContentType.text) {
    try {
      _body = utf8.decode(uInt8List);
    } on Exception {
      _body = null;
    }
  } else if (request.headers.contentType?.mimeType ==
      ContentType.binary.mimeType) {
    try {
      _body = (uInt8List);
    } on Exception {
      _body = null;
    }
  } else {
    try {
      _body = json.decode(utf8.decode(uInt8List));
    } on Exception {
      try {
        _body = utf8.decode(uInt8List);
      } on Exception {
        try {
          _body = (uInt8List);
        } on Exception {
          _body = null;
        }
      }
    }
  }

  var req = await HttpStyleRequest.fromRequest(
      req: request, body: Body(_body), context: context);
  try {
    var res = await context.owner.calling(req);
    if (res is Response && res is! NoResponseRequired) {
      request.response.statusCode = res.statusCode;

      request.response.headers.contentType = res.contentType;
      for (var head in res.additionalHeaders?.entries.toList() ??
          <MapEntry<String, dynamic>>[]) {
        request.response.headers.add(head.key, head.value);
      }

      if (res.body != null && res.body is BinaryBody) {
        request.response.add((res.body as BinaryBody).data);
      } else {
        if (res.body?.data != null) {
          request.response.write(res.body);
        }
      }

      await request.response.close();
      res.sent = true;
    }
  } on Exception catch (e) {
    request.response.statusCode = 400;
    request.response.headers.contentType = ContentType.json;
    request.response.write(json.encode({"error": e.toString()}));
    request.response.close();
  }

  return;
}