socketry / async-websocket

Asynchronous WebSocket client and server, supporting HTTP/1 and HTTP/2 for Ruby.
MIT License
167 stars 18 forks source link

Connect client with headers #3

Closed bryanp closed 5 years ago

bryanp commented 5 years ago

The client example works great, but hitting a situation where I need to connect with headers. Having trouble understanding if this is currently supported, and my attempts to do this through Async::HTTP::URLEndpoint or the client connection itself haven't panned out.

ioquatix commented 5 years ago

(Previous reply was wrong) Actually my bad, it just occurred to me there might be a method to set headers and there it is: https://github.com/faye/websocket-driver-ruby/blob/ee39af83d03ae3059c775583e4c4b291641257b8/lib/websocket/driver.rb#L96

We already expose client.driver so it should be as simple as calling client.driver.set_header at the appropriate place... or adding it to a constructor.

bryanp commented 5 years ago

Got it. Since Async::WebSocket::Connection calls driver.start in initialize, would have to do:

module Async
  module WebSocket
    class Client < Async::WebSocket::Connection
      def initialize(socket, url = "ws://.", headers = {})
        @url = url

        super socket, build_client(headers)
      end

      private

      def build_client(headers)
        ::WebSocket::Driver.client(self).tap do |client|
          headers.each do |key, value|
            client.set_header(key, value)
          end
        end
      end
    end
  end
end

I confirmed this worked for my use-case. If you're interested in supporting in the library, I'll open a PR.

ioquatix commented 5 years ago

Yes please make pr:)