serve method

Future<HttpServer> serve({
  1. InternetAddress? host,
  2. int? port,
  3. CorsOptions? cors,
})

Starts a standalone HTTP server for the registered routes.

  • host defaults to InternetAddress.anyIPv4, which is what container platforms such as Cloud Run expect. Pass InternetAddress.loopbackIPv4 to only accept local connections.
  • port defaults to the PORT environment variable, then 3400. Pass 0 to pick a free port (read it back from HttpServer.port).
  • cors enables CORS handling. When null, no CORS headers are sent and browsers on other origins can't call the server.

Unknown paths get a 404. Routes added after the server starts are served too. Stop the server with HttpServer.close.

The bound address is logged at INFO on the genkit.server logger (package:logging), which prints nothing until a listener is attached:

Logger.root.onRecord.listen(print);
await genkit.serve(); // Genkit server listening on http://0.0.0.0:3400

Implementation

Future<HttpServer> serve({
  InternetAddress? host,
  int? port,
  CorsOptions? cors,
}) async {
  final server = await HttpServer.bind(
    host ?? InternetAddress.anyIPv4,
    port ?? int.tryParse(Platform.environment['PORT'] ?? '') ?? 3400,
  );

  Future<GenkitHttpResponse> dispatch(GenkitHttpRequest request) async =>
      await handle(request) ?? _notFound();

  server.listen((request) async {
    try {
      final path = decodeRequestPath(request.uri.path);
      if (path == null) {
        await writeHttpResponse(_notFound(), request.response);
        return;
      }
      final genkitRequest = toGenkitHttpRequest(request, path: path);
      // CORS wraps the 404 too, so browser code can read it.
      final response = cors == null
          ? await dispatch(genkitRequest)
          : await withCors(cors, genkitRequest, dispatch);
      await writeHttpResponse(response, request.response);
    } catch (e, st) {
      // actionHandler turns action errors into responses, so this is a
      // transport failure (e.g. the client went away mid-response).
      _logger.warning('Failed to serve ${request.uri.path}', e, st);
    }
  });

  _logger.info(
    'Genkit server listening on '
    'http://${server.address.address}:${server.port}',
  );
  for (final path in _routes.keys) {
    _logger.fine('  POST $path');
  }
  return server;
}