Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Serve Files With HttpServer In Dart

Tags:

dart

dart-io

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:

        }
      });
    });
}
like image 393
Peter Avatar asked Feb 28 '26 09:02

Peter


2 Answers

Here is the latest version of my code after Matt B's answer:

import 'dart:io';
import 'package:path/path.dart' as path;

String _basePath;

_sendNotFound(HttpResponse response) {
  response.write('Not found');
  response.statusCode = HttpStatus.NOT_FOUND;
  response.close();
}


_handleGet(HttpRequest request) {
  // PENDING: Do more security checks here?
  final String stringPath = request.uri.path == '/' ? '/main.html' : request.uri.path;
  final File file = new File(path.join(_basePath, stringPath));
  file.exists().then((bool found) {
    if (found) {
      file.openRead().pipe(request.response).catchError((e) { });
    } else {
      _sendNotFound(request.response);
    }
  });
}


_handlePost(HttpRequest request) {

}


void main() {
  _basePath = Platform.environment['HOME'];

  HttpServer.bind('127.0.0.1', 80).then((HttpServer server) {
    server.listen((request) { 
      switch (request.method) {
        case 'GET':
          _handleGet(request);
          break;

        case 'POST':
          _handlePost(request);
          break;

        default:
          request.response.statusCode = HttpStatus.METHOD_NOT_ALLOWED;
          request.response.close();
      }
    });
  });
}
like image 106
Peter Avatar answered Mar 01 '26 23:03

Peter


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).

like image 26
Matt B Avatar answered Mar 02 '26 00:03

Matt B