startLocalServer function

Future<HttpServer> startLocalServer(
  1. String directory
)

Implementation

Future<HttpServer> startLocalServer(String directory) async {
  // If server is already running, close it first
  if (_activeServer != null) {
    try {
      h5pLog(message: '๐Ÿงน Closing previous local server...');
      await _activeServer!.close(force: true);
      _activeServer = null;
    } catch (e) {
      h5pErrorLog(message: 'โš ๏ธ Error closing previous server: $e');
    }
  }

  // Create a static file handler
  final handler = createStaticHandler(
    directory,
    defaultDocument: 'index.html',
    serveFilesOutsidePath: true,
  );

  // Try to start the new server
  try {
    final server = await shelf_io.serve(
      handler,
      InternetAddress.loopbackIPv4,
      h5pPort,
      shared: true, // allow multiple bindings safely
    );

    _activeServer = server;
    h5pLog(
        message:
            '๐ŸŒ Local server.dart running at: http://${server.address.address}:${server.port}');
    return server;
  } catch (e) {
    h5pErrorLog(message: 'โŒ Failed to start server: $e');
    rethrow;
  }
}