How To Serve Files With HttpServer In Dart

回眸只為那壹抹淺笑 提交于 2020-04-10 05:42:41

问题


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:

        }
      });
    });
}

回答1:


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




回答2:


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();
      }
    });
  });
}



回答3:


What you are looking for is already included in pub.

$ pub serve --help

Run a local web development server.

By default, this serves "web/" and "test/", but an explicit list of 
directories to serve can be provided as well.

Usage: pub serve [directories...]
-h, --help               Print this usage information.
    --mode               Mode to run transformers in.
                         (defaults to "debug")

    --all                Use all default source directories.
-D, --define             Defines an environment constant for dart2js.
    --hostname           The hostname to listen on.
                         (defaults to "localhost")

    --port               The base port to listen on.
                         (defaults to "8080")

    --[no-]dart2js       Compile Dart to JavaScript.
                         (defaults to on)

    --[no-]force-poll    Force the use of a polling filesystem watcher.

Run "pub help" to see global options.

See http://dartlang.org/tools/pub/cmd/pub-serve.html for detailed documentation.



来源:https://stackoverflow.com/questions/19934575/how-to-serve-files-with-httpserver-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!