HttpRoute constructor

HttpRoute(
  1. String route,
  2. FutureOr callback(
    1. HttpRequest req,
    2. HttpResponse res
    ),
  3. Method method, {
  4. List<FutureOr Function(HttpRequest req, HttpResponse res)> middleware = const [],
})

Implementation

HttpRoute(this.route, this.callback, this.method,
    {this.middleware = const []})
    : usesWildcardMatcher = route.contains('*') {
  // Split route path into segments
  final segments = Uri.tryParse(route.normalizePath)?.pathSegments ??
      [route.normalizePath];

  var pattern = '^';
  for (var segment in segments) {
    if (segment == '*' &&
        segment != segments.first &&
        segment == segments.last) {
      // Generously match path if last segment is wildcard (*)
      // Example: 'some/path/*' => should match 'some/path', 'some/path/', 'some/path/with/children'
      //                           but not 'some/pathological'
      pattern += r'(?:/.*|)';
      break;
    } else if (segment != segments.first) {
      // Add path separators
      pattern += '/';
    }

    // parse parameter if any
    final param = HttpRouteParam.tryParse(segment);
    if (param != null) {
      if (_params.containsKey(param.name)) {
        throw DuplicateParameterException(param.name);
      }
      _params[param.name] = param;
      segment = r'(?<' + param.name + r'>' + param.pattern + ')';
    } else {
      // escape period character
      segment = segment.replaceAll('.', r'\.');
      // wildcard ('*') to anything
      segment = segment.replaceAll('*', '.*?');
    }

    pattern += segment;
  }

  pattern += r'$';
  matcher = RegExp(pattern, caseSensitive: false);
}