open method

  1. @override
Future open ()

Begins listening for HTTP requests on port.

Implementation

@override
Future open() async {
  server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, port);
  server.listen((HttpRequest req) async {
    final mockReq = new MockHTTPRequest()
      ..method = req.method
      ..path = req.uri.path
      ..queryParameters = req.uri.queryParameters;

    mockReq.headers = {};
    req.headers.forEach((name, values) {
      mockReq.headers[name] = values.join(",");
    });

    if (req.contentLength > 0) {
      mockReq.body = new String.fromCharCodes(await req.first);
    }

    add(mockReq);

    Response response;
    Duration delay = defaultDelay;

    if (_responseQueue.length > 0) {
      final mockResp = _responseQueue.removeAt(0);

      if (mockResp.response.statusCode == _mockConnectionFailureStatusCode) {
        // We let this one die by not responding.
        return null;
      }

      if (mockResp.delay != null) {
        delay = mockResp.delay;
      }

      response = mockResp.response;
    } else {
      response = defaultResponse;
    }

    if (delay != null) {
      await new Future.delayed(delay);
    }

    final wrappedReq = new Request(req);
    wrappedReq.respond(response);
  });
}