handle method

Future<void> handle(
  1. Request req,
  2. ResponseContract res
)

Implementation

Future<void> handle(Request req, ResponseContract res) async {
  final match = router.match(req.method, req.path);

  if (match != null && ServerContext.hasContext) {
    ServerContext.current.setMatch(match);
  }

  if (match == null) {
    if (staticHandler != null && res is Response) {
      if (await staticHandler!.tryServe(req, res)) {
        return;
      }
    }
    res.status(404).send('Not Found');
    return;
  }

  // Set route parameters
  match.params.forEach((key, value) {
    req.setParam(key, value);
  });

  // Execute route-specific middleware and then the handler
  // We use the optimized static execute method to avoid allocations
  await MiddlewarePipeline.execute(
    match.middleware,
    req,
    res,
    (request, response) {
      if (response is! Response) {
        throw StateError(
          'HTTP route handlers require a concrete Response instance.',
        );
      }
      return match.handler(request, response);
    },
  );
}