handleRequest method

Future<bool> handleRequest(
  1. RequestContext req,
  2. ResponseContext res
)

Handles an incoming HTTP request.

Refuses, before it is upgraded, a connection from an origin that allowedOrigins does not allow, or that asks only for protocols that allowedProtocols does not allow. WebSockets over HTTP/2 are not supported; such a request is refused with a 501 Not Implemented.

Implementation

Future<bool> handleRequest(RequestContext req, ResponseContext res) async {
  if (req is HttpRequestContext && res is HttpResponseContext) {
    if (!WebSocketTransformer.isUpgradeRequest(req.rawRequest!)) {
      throw AngelHttpException.badRequest();
    }
    _checkOrigin(req);
    var protocol = _protocolOf(req);

    res.detach();
    var ws = await WebSocketTransformer.upgrade(
      req.rawRequest!,
      protocolSelector: protocol == null ? null : (_) => protocol,
    );
    var channel = IOWebSocketChannel(ws);
    var socket = WebSocketContext(channel, req, res, serializer: serializer);
    scheduleMicrotask(() => handleClient(socket));
    return false;
  } else if (req is Http2RequestContext && res is Http2ResponseContext) {
    // HTTP/2 has no `Connection: upgrade`; WebSockets over it use an
    // extended CONNECT (RFC 8441), which this does not support.
    throw AngelHttpException(
      statusCode: 501,
      message:
          'WebSockets over HTTP/2 are not supported. Connect over HTTP/1.1.',
    );
  } else {
    throw ArgumentError(
      'Not an HTTP/1.1 or HTTP/2 RequestContext+ResponseContext pair: $req, $res',
    );
  }
}