Search code examples
dartdart-io

How To Serve Files With HttpServer In Dart


I have the following standard structure for my Dart app:

/
  pubspec.yaml
  web/
    main.css
    main.dart
    main.html
  build.dart
  server.dart

When I receive GET requests on the server, I want the server to use the web directory as root and serve the content of the files to clients.

How can I do this?

This is how far I've gotten so far:

import 'dart:io';

void main() {
    HttpServer.bind('127.0.0.1', 80).then((HttpServer server) {
      server.listen((request) { 
        print("got request");

        switch (request.method) {
          case 'GET':
            // Do I need to send the file here? ... 
            // if not fount then send HttpStatus.NOT_FOUND;
            break;

          default:

        }
      });
    });
}

Solution

  • The Dart website contains a small sample on Writing web servers which shows how to serve pages. in your case because your server.dart file is in the root directory (for future reference, it's generally recommended that CLI scripts designed to be run be held in a bin directory per the Package Layout Conventions), you will need to append 'web/' to the arguments passed to the script.

    Additionally, note that the 'Options' class used in the sample has been deprecated and you should use the dart:io Platform.script property instead.

    That said, I highly suggest you look at using the route package to handle server requests as it easily allows for assigning various callbacks depending on a matching pattern (including request methods).