OLD | NEW |
---|---|
(Empty) | |
1 #library('http_server'); | |
ahe
2012/10/04 10:06:43
Missing copyright.
Mads Ager (google)
2012/10/04 10:21:51
Done.
| |
2 | |
3 #import('dart:io'); | |
4 #import('test_suite.dart'); // For TestUtils. | |
5 | |
6 HttpServer _httpServer; | |
7 | |
8 startHttpServer(String host, int port) { | |
9 var basePath = TestUtils.dartDir(); | |
10 _httpServer = new HttpServer(); | |
11 _httpServer.listen(host, port); | |
ricow1
2012/10/04 10:28:06
shouldn't we set the error handler before calling
Mads Ager (google)
2012/10/04 10:41:42
I have moved it. It doesn't really matter at this
| |
12 _httpServer.onError = (e) { | |
13 // Consider errors in the builtin http server fatal. | |
14 // Intead of just throwing the exception we print | |
15 // a message that makes it clearer what happened. | |
16 print('Test http server error: $e'); | |
17 exit(1); | |
18 }; | |
19 _httpServer.defaultRequestHandler = (request, resp) { | |
20 var requestPath = new Path(request.path).canonicalize(); | |
21 if (!requestPath.isAbsolute) { | |
22 resp.statusCode = HttpStatus.NOT_FOUND; | |
23 resp.outputStream.close(); | |
24 } else { | |
25 var path = basePath; | |
26 requestPath.segments().forEach((s) => path = path.append(s)); | |
27 var file = new File(path.toNativePath()); | |
28 file.exists().then((exists) { | |
29 if (exists) { | |
30 // Allow loading from localhost in browsers. | |
31 resp.headers.set("Access-Control-Allow-Origin", "*"); | |
32 file.openInputStream().pipe(resp.outputStream); | |
33 } else { | |
34 resp.statusCode = HttpStatus.NOT_FOUND; | |
35 resp.outputStream.close(); | |
36 } | |
37 }); | |
38 } | |
39 }; | |
40 } | |
41 | |
42 terminateHttpServer() { | |
43 _httpServer.close(); | |
44 } | |
OLD | NEW |