OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library shelf_static.example; |
| 6 |
| 7 import 'dart:io'; |
| 8 import 'package:args/args.dart'; |
| 9 import 'package:shelf/shelf.dart' as shelf; |
| 10 import 'package:shelf/shelf_io.dart' as io; |
| 11 import 'package:shelf_static/shelf_static.dart'; |
| 12 |
| 13 void main(List<String> args) { |
| 14 var parser = _getParser(); |
| 15 |
| 16 int port; |
| 17 bool logging; |
| 18 bool listDirectories; |
| 19 |
| 20 try { |
| 21 var result = parser.parse(args); |
| 22 port = int.parse(result['port']); |
| 23 logging = result['logging']; |
| 24 listDirectories = result['list-directories']; |
| 25 } on FormatException catch (e) { |
| 26 stderr.writeln(e.message); |
| 27 stderr.writeln(parser.usage); |
| 28 // http://linux.die.net/include/sysexits.h |
| 29 // #define EX_USAGE 64 /* command line usage error */ |
| 30 exit(64); |
| 31 } |
| 32 |
| 33 if (!FileSystemEntity.isFileSync('example/example_server.dart')) { |
| 34 throw new StateError('Server expects to be started the ' |
| 35 'root of the project.'); |
| 36 } |
| 37 var pipeline = const shelf.Pipeline(); |
| 38 |
| 39 if (logging) { |
| 40 pipeline = pipeline.addMiddleware(shelf.logRequests()); |
| 41 } |
| 42 |
| 43 var defaultDoc = _defaultDoc; |
| 44 if (listDirectories) { |
| 45 defaultDoc = null; |
| 46 } |
| 47 |
| 48 var handler = pipeline.addHandler(createStaticHandler('example/files', |
| 49 defaultDocument: defaultDoc, listDirectories: listDirectories)); |
| 50 |
| 51 io.serve(handler, 'localhost', port).then((server) { |
| 52 print('Serving at http://${server.address.host}:${server.port}'); |
| 53 }); |
| 54 } |
| 55 |
| 56 ArgParser _getParser() => new ArgParser() |
| 57 ..addFlag('logging', abbr: 'l', defaultsTo: true, negatable: true) |
| 58 ..addOption('port', abbr: 'p', defaultsTo: '8080') |
| 59 ..addFlag('list-directories', |
| 60 abbr: 'f', |
| 61 defaultsTo: false, |
| 62 negatable: false, |
| 63 help: 'List the files in the source directory instead of servering the def
ault document - "$_defaultDoc".'); |
| 64 |
| 65 const _defaultDoc = 'index.html'; |
OLD | NEW |