serveHTTP method

Future serveHTTP()

Implementation

Future serveHTTP() async {
  final port = container.read('@config.app.port') ?? 4040;
  server = await HttpServer.bind(
    InternetAddress.anyIPv6,
    port,
  );

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

  await for (HttpRequest request in server!) {
    var hasMatch = false;
    for (var i = 0; i < bindings.length; i++) {
      final params = <String>[];

// Get the root pattern from the pathToRegex call
      final rootPattern = pathToRegExp(bindings[i].path,
              parameters: params, prefix: bindings[i].isPrefixBinding)
          .pattern;

      // TODO: Circumvent this for prefix bindings I guess?

      // Build a new regex by removing the $, adding in the optional trailing slash
      // and then adding the end terminator back on ($).
      var cleanedPattern =
          rootPattern.substring(0, rootPattern.lastIndexOf('\$'));
      // account for the path already ending in slash
      if (cleanedPattern.endsWith('/')) {
        cleanedPattern =
            cleanedPattern.substring(0, cleanedPattern.length - 1);
      }
      final regex = RegExp(
          '$cleanedPattern\\/?${bindings[i].isPrefixBinding ? '\$)' : '\$'}',
          caseSensitive: false);
      hasMatch = regex.hasMatch(request.uri.path);

      if (hasMatch) {
        final match = regex.matchAsPrefix(request.uri.path);
        if (match != null) {
          final pathParams = extract(params, match);

          final ctx = StewardContext(
              request: Request(request: request, pathParams: pathParams),
              container: container.clone());

          await processHandlersWithMiddleware(
              bindings[i].process,
              [
                ...bindings[i].middleware.reversed,
                ...middleware.reversed,
              ],
              ctx,
              request);
          break;
        }
      }
    }

    if (!hasMatch) {
      await processHandlersWithMiddleware(
          (Context context) => Future.value(Response.NotFound()),
          [...middleware.reversed],
          StewardContext(
              request: Request(request: request),
              container: container.clone()),
          request);
    }

    await request.response.close();
  }
}