getHandler method

  1. @override
Object? getHandler(
  1. HttpConnect connect,
  2. String uri
)
override

Retrieves the first matched request handler (RequestHandler) or forwarded URI (String) for the given URI.

Implementation

@override
Object? getHandler(HttpConnect connect, String uri) {
  //check cache first before shallCache => better performance
  //reason: shallCache is likely to return true (after regex)
  final cache = _uriCache.getCache(connect, _uriMapping);
  var handler = cache[uri];

  if (handler == null) {
    _UriMapping? mp;
    for (mp in _uriMapping)
      if (mp.match(connect, uri)) {
        handler = mp.handler;
        break;
      }

    //store to cache
    if (shallCache(connect, uri)) {
      cache[uri] = handler == null ? _notFound:
          mp!.hasNamedGroup ? mp: handler;
          //store _UriMapping if containing named group, so `mp.match()`
          //will be called when matched, see 6th line below
      if (cache.length > _cacheSize)
        cache.remove(cache.keys.first);
    }
  } else if (identical(handler, _notFound)) {
    return null;
  } else if (handler is _UriMapping) { //hasGroup
    handler.match(connect, uri);
      //prepare for [getNamedGroup], since [_setUriMatch]'ll be called
    handler = handler.handler;
  }

  if (handler is List) {
    final sb = StringBuffer();
    for (var seg in handler) {
      if (seg is _Var) {
        seg = getNamedGroup(connect, seg.name);
        if (seg == null) continue; //skip
      }
      sb.write(seg);
    }
    return sb.toString();
  }
  return handler;
}