How to use Dart http_server: VirtualDirectory

I use dart:route api to serve static files, but I noticed that there is a main library called http_server that contains helper classes and functions for dart:io HttpServer .

Of particular interest to me is the VirtualDirectory class, which, according to the docs, takes a String object for the static contents of the directory, and then you call the serve() method

 var virtualDirectory = new VirtualDirectory('/var/www/'); virtualDirectory.serve(new HttpServer('0.0.0.0', 8080)); 

This does not work because there is no constructor for HttpServer - at least in current versions.

 virtualDirectory.serve(HttpServer.bind('0.0.0.0', 8080)); 

The way I created the server instance also fails, since virtualDirectory.serve() does not accept Future<HttpServer> and finally:

 virtualDirectory.serve(HttpServer.bind('0.0.0.0', 8080).asStream()); 

also fails with the argument type "Stream" cannot be assigned to the parameter type 'Stream'

So how do I connect VirtualDirectory to the server? There are no examples that I can find on the Internet, and the source code of VirtualDirectory does not make it clear. I would have RTFM if I could FTFM. Links are in order as answers.

+7
dart dart-io
source share
1 answer

VirtualDirectory can work from within the future returned by HttpServer.bind . You can create a web server for a static file using the following five lines of code:

 HttpServer.bind('127.0.0.1', 8888).then((HttpServer server) { VirtualDirectory vd = new VirtualDirectory('../web/'); vd.jailRoot = false; vd.serve(server); }); 

You can make it more complex by parsing the URI and pulling out service requests before the files are uploaded.

 import 'dart:io'; import 'package:http_server/http_server.dart'; main() { handleService(HttpRequest request) { print('New service request'); request.response.write('[{"field":"value"}]'); request.response.close(); }; HttpServer.bind('127.0.0.1', 8888).then((HttpServer server) { VirtualDirectory vd = new VirtualDirectory('../web/'); vd.jailRoot = false; server.listen((request) { print("request.uri.path: " + request.uri.path); if (request.uri.path == '/services') { handleService(request); } else { print('File request'); vd.serveRequest(request); } }); }); } 
+9
source

All Articles