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.io_server; |
| 6 |
| 7 import 'dart:async'; |
| 8 |
| 9 import 'dart:io'; |
| 10 |
| 11 import '../shelf_io.dart'; |
| 12 import 'handler.dart'; |
| 13 import 'server.dart'; |
| 14 |
| 15 /// A [Server] backed by a `dart:io` [HttpServer]. |
| 16 class IOServer implements Server { |
| 17 /// The underlying [HttpServer]. |
| 18 final HttpServer server; |
| 19 |
| 20 /// Whether [mount] has been called. |
| 21 bool _mounted = false; |
| 22 |
| 23 Uri get url { |
| 24 if (server.address.isLoopback) { |
| 25 return new Uri(scheme: "http", host: "localhost", port: server.port); |
| 26 } |
| 27 |
| 28 // IPv6 addresses in URLs need to be enclosed in square brackets to avoid |
| 29 // URL ambiguity with the ":" in the address. |
| 30 if (server.address.type == InternetAddressType.IP_V6) { |
| 31 return new Uri( |
| 32 scheme: "http", |
| 33 host: "[${server.address.address}]", |
| 34 port: server.port); |
| 35 } |
| 36 |
| 37 return new Uri( |
| 38 scheme: "http", host: server.address.address, port: server.port); |
| 39 } |
| 40 |
| 41 /// Calls [HttpServer.bind] and wraps the result in an [IOServer]. |
| 42 static Future<IOServer> bind(address, int port, {int backlog}) async { |
| 43 backlog ??= 0; |
| 44 var server = await HttpServer.bind(address, port, backlog: backlog); |
| 45 return new IOServer(server); |
| 46 } |
| 47 |
| 48 IOServer(this.server); |
| 49 |
| 50 void mount(Handler handler) { |
| 51 if (_mounted) { |
| 52 throw new StateError("Can't mount two handlers for the same server."); |
| 53 } |
| 54 _mounted = true; |
| 55 |
| 56 serveRequests(server, handler); |
| 57 } |
| 58 |
| 59 Future close() => server.close(); |
| 60 } |
OLD | NEW |