handleHttpRequest method

Future<bool> handleHttpRequest(
  1. HttpRequest request, {
  2. String basePath = '',
  3. CorsOptions? cors,
})

Handles a dart:io request if it targets one of the registered routes, and returns whether it did.

Routes are matched below basePath (e.g. /api, so /api/myFlow hits the /myFlow route). When this returns false the request is untouched, so you can route it elsewhere:

await for (final request in server) {
  if (await genkit.handleHttpRequest(request, basePath: '/api')) continue;
  request.response
    ..statusCode = HttpStatus.notFound
    ..close();
}

cors enables CORS handling (including preflight OPTIONS) for the routes of this router.

Throws an ArgumentError if basePath is not empty and doesn't start with / or ends with /.

Implementation

Future<bool> handleHttpRequest(
  HttpRequest request, {
  String basePath = '',
  CorsOptions? cors,
}) async {
  if (basePath.isNotEmpty &&
      (!basePath.startsWith('/') || basePath.endsWith('/'))) {
    throw ArgumentError.value(
      basePath,
      'basePath',
      "must be empty, or start with '/' and not end with '/'",
    );
  }
  // Route keys are raw action names, so match on the decoded path (e.g.
  // `googleai%2Fgemini-flash-latest`). A bad escape can't name a route.
  final fullPath = decodeRequestPath(request.uri.path);
  if (fullPath == null) return false;
  final String path;
  if (basePath.isEmpty) {
    path = fullPath;
  } else if (fullPath == basePath) {
    path = '/';
  } else if (fullPath.startsWith('$basePath/')) {
    path = fullPath.substring(basePath.length);
  } else {
    return false;
  }
  final handler = _routes[path];
  if (handler == null) return false;

  final genkitRequest = toGenkitHttpRequest(request, path: path);
  final response = cors == null
      ? await handler(genkitRequest)
      : await withCors(cors, genkitRequest, handler);
  await writeHttpResponse(response, request.response);
  return true;
}