dispatch method

void dispatch(
  1. HttpRequest request
)

Implementation

void dispatch(HttpRequest request) async {

  final method = _parseMethod(request.method);
  final path = _normalize(request.uri.path);

  // 1) Try static first
  final handler = _routes[method]?[path];
  final middleware = _middlewareMap[path] ?? [];

  if (handler != null) {
    _runMiddleware(request, middleware, 0, () async => await handler(request));
    return;
  }

  // 2) Try dynamic
  final compiled = _dynamicRoutes[method] ?? const [];
  for (final cr in compiled) {
    final m = cr.regex.firstMatch(path);
    if (m == null) continue;

    // Coerce captured groups by type
    final params = <String, dynamic>{};
    var ok = true;

    for (var i = 0; i < cr.paramNames.length; i++) {
      final raw = m.group(i + 1)!;
      final typeName = cr.paramTypes[i];
      final coerced = _coerce(raw, typeName);
      if (coerced == _Coerce.fail) {
        ok = false;
        break;
      }
      params[cr.paramNames[i]] = coerced is _Coerce ? coerced.value : coerced;
    }

    if (!ok) continue; // wrong type; keep looking

    // Run the pipeline with params available via RouteParams.get<T>()
    runZoned(
          () => _runMiddleware(
        request,
        cr.middleware,
        0,
            () => cr.handler(request),
      ),
      zoneValues: RouteParams._zoneValues(params),
    );
    return;
  }

  // 3) Not found
  request.notFound();
}