bind static method

Future<HttpServer> bind(
  1. ServerHandler handler, {
  2. ServerErrorHandler? onError,
  3. Object? address,
  4. int port = 3000,
  5. int backlog = 0,
  6. bool shared = false,
  7. Directory? publicDirectory,
  8. bool compressStaticAssets = true,
  9. File? developmentProxyOriginFile,
})

Starts an HTTP server that forwards requests to handler.

Files in publicDirectory use conditional caching and stream eligible responses with gzip when compressStaticAssets is enabled. Exact files take priority; HTML-compatible requests fall back to an index.html below the requested path.

onError reports unexpected failures owned by this adapter, including static files, the development proxy, response metadata, framing, and omitted response bodies from raw handlers. Handler and source-stream failures remain owned by handler. The default writes to the current Dart Zone; pass an explicit no-op to disable reporting. The callback starts after the server-side response close attempt settles. Its future is observed by the detached request task, which HttpServer.close does not await, so keep reporting bounded and use an application-owned durable queue when delivery must survive shutdown.

Implementation

static Future<HttpServer> bind(
  ServerHandler handler, {
  ServerErrorHandler? onError,
  Object? address,
  int port = 3000,
  int backlog = 0,
  bool shared = false,
  Directory? publicDirectory,
  bool compressStaticAssets = true,
  File? developmentProxyOriginFile,
}) async {
  final server = await HttpServer.bind(
    address ?? InternetAddress.loopbackIPv4,
    port,
    backlog: backlog,
    shared: shared,
  );
  final lifecycle = _IoServerLifecycle();
  _lifecycles[server] = lifecycle;
  final listening = _listen(
    server,
    handler,
    onError ?? defaultServerErrorHandler,
    publicDirectory == null
        ? null
        : StaticFiles(publicDirectory, compress: compressStaticAssets),
    developmentProxyOriginFile == null
        ? null
        : DevelopmentProxy(developmentProxyOriginFile.absolute),
    lifecycle,
  );
  lifecycle.listening = listening;
  unawaited(
    listening.then<void>((_) {}, onError: _reportDetachedTaskFailure),
  );
  return server;
}