2

I'm looking for guidance on how to improve this file server.

Currently it can't handle POSTs because each request is handed off to the http_server lib. It also routes URLs naively; can this be improved using Routers? Maybe the path lib can help, too?

import 'dart:io';
import 'package:http_server/http_server.dart';

// TODO: use these imports :)
import 'package:path/path.dart' as path;
import 'package:route/url_pattern.dart';

final address = InternetAddress.LOOPBACK_IP_V4;
const port = 4040;

final buildPath = Platform.script.resolve('web');
final publicDir = new VirtualDirectory(buildPath.toFilePath());

main() async {
  // Override directory listing
  publicDir
    ..allowDirectoryListing = true
    ..directoryHandler = handleDir
    ..errorPageHandler = handleError;

  // Start the server
  final server = await HttpServer.bind(address, port);
  print('Listening on port $port...');
  await server.forEach(publicDir.serveRequest);
}

// Handle directory requests
handleDir(dir, req) async {
  var indexUri = new Uri.file(dir.path).resolve('index.html');
  var index = new File.fromUri(indexUri);
  if (!await index.exists()) {
    handleError(req);
    return;
  }
  publicDir.serveFile(index, req);
}

// Handle error responses
handleError(req) {
  req.response.statusCode = HttpStatus.NOT_FOUND;
  var errorUri = new Uri.directory(publicDir.root).resolve('error.html');
  var errorPage = new File.fromUri(errorUri);
  publicDir.serveFile(errorPage, req);
}
Ganymede
  • 3,345
  • 1
  • 22
  • 17

2 Answers2

2

I don't see a way around this

await for (var req in server) {
  // distribute requests to different handlers
  if(req.method == 'POST') {

  } else {
    publicDir.serveRequest(req);
  }
}

Alternatively you can use the shelf package with shelf_route and shelf_static which allows you to assign requests and handlers in a more declarative style but which do the same under the hood

https://pub.dartlang.org/search?q=shelf_static

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

shelf_static is excellent for file servers, and servers with routing can be done with shelf_route.

import 'dart:io';

import 'package:shelf_io/shelf_io.dart' as io;
import 'package:shelf_static/shelf_static.dart';
import 'package:path/path.dart' show join, dirname;

final address = InternetAddress.LOOPBACK_IP_V4;
const port = 8080;

main() async {
  var staticPath = join(dirname(Platform.script.toFilePath()), '..', 'web');
  var staticHandler = createStaticHandler(staticPath, defaultDocument: 'index.html');
  var server = await io.serve(staticHandler, address, port);
}
Ganymede
  • 3,345
  • 1
  • 22
  • 17