start method
Implementation
Future<void> start(int port) async {
close();
// Bind to local loopback
_server = await HttpServer.bind(InternetAddress.loopbackIPv4, port);
if (kDebugMode) {
print('[WebServer] Serving at http://${_server!.address.address}:$port');
print('[WebServer] Assets directory: $_assetsDir');
}
_server!.listen((HttpRequest request) async {
// Default to /index.html if path == "/"
final path = request.uri.path == '/' ? '/index.html' : request.uri.path;
// Build the full asset key by combining your custom directory + requested path
final assetKey = '$_assetsDir$path';
try {
// Load from Flutter asset bundle
final data = await rootBundle.load(assetKey);
final bytes = data.buffer.asUint8List();
// Use mime to guess content type from file path
final mimeStr = lookupMimeType(assetKey) ?? 'application/octet-stream';
ContentType contentType;
try {
contentType = ContentType.parse(mimeStr);
} catch (_) {
contentType = ContentType.binary;
}
// Write response
request.response.statusCode = HttpStatus.ok;
request.response.headers.contentType = contentType;
request.response.add(bytes);
} catch (e) {
// If not found or error reading => 404
request.response.statusCode = HttpStatus.notFound;
request.response.write('404 Not Found');
} finally {
await request.response.close();
}
});
}