OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2012, 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('http_server'); |
| 6 |
| 7 #import('dart:io'); |
| 8 #import('test_suite.dart'); // For TestUtils. |
| 9 |
| 10 HttpServer _httpServer; |
| 11 |
| 12 startHttpServer(String host, int port) { |
| 13 var basePath = TestUtils.dartDir(); |
| 14 _httpServer = new HttpServer(); |
| 15 _httpServer.onError = (e) { |
| 16 // Consider errors in the builtin http server fatal. |
| 17 // Intead of just throwing the exception we print |
| 18 // a message that makes it clearer what happened. |
| 19 print('Test http server error: $e'); |
| 20 exit(1); |
| 21 }; |
| 22 _httpServer.defaultRequestHandler = (request, resp) { |
| 23 var requestPath = new Path(request.path).canonicalize(); |
| 24 if (!requestPath.isAbsolute) { |
| 25 resp.statusCode = HttpStatus.NOT_FOUND; |
| 26 resp.outputStream.close(); |
| 27 } else { |
| 28 var path = basePath; |
| 29 requestPath.segments().forEach((s) => path = path.append(s)); |
| 30 var file = new File(path.toNativePath()); |
| 31 file.exists().then((exists) { |
| 32 if (exists) { |
| 33 // Allow loading from localhost in browsers. |
| 34 resp.headers.set("Access-Control-Allow-Origin", "*"); |
| 35 file.openInputStream().pipe(resp.outputStream); |
| 36 } else { |
| 37 resp.statusCode = HttpStatus.NOT_FOUND; |
| 38 resp.outputStream.close(); |
| 39 } |
| 40 }); |
| 41 } |
| 42 }; |
| 43 _httpServer.listen(host, port); |
| 44 } |
| 45 |
| 46 terminateHttpServer() { |
| 47 _httpServer.close(); |
| 48 } |
OLD | NEW |