serveHTTP method

Future serveHTTP()

Implementation

Future serveHTTP() async {
  var port = container?.make('@config.app.port') ?? 4040;
  server = await HttpServer.bind(
    InternetAddress.loopbackIPv4,
    port,
  );

  print('Bound server to port ${port}');

  await for (HttpRequest request in server!) {
    var hasMatch = false;
    for (var i = 0; i < bindings.length; i++) {
      var params = <String>[];
      var regex = pathToRegExp(bindings[i].path, parameters: params);
      hasMatch = regex.hasMatch(request.uri.path);

      if (hasMatch) {
          var match = regex.matchAsPrefix(request.uri.path);
          if (match != null) {
            var pathParams = extract(params, match);
            var req = Request(request: request, pathParams: pathParams)..setContainer(container);

            // process router level middleware
            if (middleware.isNotEmpty) {
              middleware.forEach((element) {
                element(req);
              });
            }

            // process binding level middleware
            if (bindings[i].middleware.isNotEmpty) {
              bindings[i].middleware.forEach((element) {
                element(req);
              });
            }

            var response = bindings[i].process(req);
            _renderResponse(request, response);
            break;
        }
      }
    }

    if (!hasMatch) {
      var req = Request(request: request)..setContainer(container);
      // process router level middleware
      if (middleware.isNotEmpty) {
        middleware.forEach((element) {
          element(req);
        });
      }
      request.response.statusCode = 404;
    }

    await request.response.close();
  }
}