💡

【Ruby】Protocol::HTTP2 で HTTP/2 フレームを送信する

2024/07/09に公開

HTTP/2 対応サーバーの Falcon に使われている Protocol::HTTP2 を使ってみた。わかりやすい。以下の gems をあらかじめインストールした

gem install async async-io protocol-http2
client.rb
# https://github.com/socketry/protocol-http2/blob/main/examples/http2/request.rb

require 'async'
require 'async/io/stream'
require 'async/http/endpoint'
require 'protocol/http2/client'

Async do
        endpoint = Async::HTTP::Endpoint.parse("http://0.0.0.0:8000")

        peer = endpoint.connect

        puts "Connected to #{peer.inspect}"

        # IO Buffering...
        stream = Async::IO::Stream.new(peer)

        framer = Protocol::HTTP2::Framer.new(stream)
        client = Protocol::HTTP2::Client.new(framer)

        puts "Sending connection preface..."
        client.send_connection_preface

        puts "Creating stream..."
        stream = client.create_stream

        headers = [
                [":scheme", endpoint.scheme],
                [":method", "GET"],
                [":authority", "localhost"],
                [":path", endpoint.path],
                ["accept", "*/*"],
        ]

        puts "Sending request on stream id=#{stream.id} state=#{stream.state}..."
        stream.send_headers(nil, headers, Protocol::HTTP2::END_STREAM)

        def stream.process_headers(frame)
                headers = super
                puts "Got response headers: #{headers} (#{frame.end_stream?})"
        end

        def stream.process_data(frame)
            if data = super
                puts "Got response data: #{data}"
            end
        end

        until stream.closed?
                frame = client.read_frame
        end

        puts "Closing client..."
        client.close
end

Discussion