Module: Async::WebSocket::Adapters::HTTP

Includes:
Protocol::WebSocket::Headers
Defined in:
lib/async/websocket/adapters/http.rb

Class Method Summary collapse

Class Method Details

.open(request, headers: [], protocols: [], handler: Connection, extensions: ::Protocol::WebSocket::Extensions::Server.default, **options, &block) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/async/websocket/adapters/http.rb', line 22

def self.open(request, headers: [], protocols: [], handler: Connection, extensions: ::Protocol::WebSocket::Extensions::Server.default, **options, &block)
  if websocket?(request)
    headers = Protocol::HTTP::Headers[headers]
    
    # Select websocket sub-protocol:
    if requested_protocol = request.headers[SEC_WEBSOCKET_PROTOCOL]
      protocol = (requested_protocol & protocols).first
    end
    
    if extensions and extension_headers = request.headers[SEC_WEBSOCKET_EXTENSIONS]
      extensions.accept(extension_headers) do |header|
        headers.add(SEC_WEBSOCKET_EXTENSIONS, header.join(";"))
      end
    end
    
    response = Response.for(request, headers, protocol: protocol, **options) do |stream|
      framer = Protocol::WebSocket::Framer.new(stream)
      connection = handler.call(framer, protocol, extensions)
      
      yield connection
    ensure
      connection&.close
      stream.close
    end
    
    # Once we get to this point, we no longer need to hold on to the request:
    request = nil
    
    return response
  end
end

.websocket?(request) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/async/websocket/adapters/http.rb', line 18

def self.websocket?(request)
  Array(request.protocol).any? { |e| e.casecmp?(PROTOCOL) }
end