|
| 1 | +# Getting Started |
| 2 | + |
| 3 | +This guide explains how to use the `protocol-http2` gem to implement a basic HTTP/2 client. |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +Add the gem to your project: |
| 8 | + |
| 9 | +``` bash |
| 10 | +$ bundle add protocol-http2 |
| 11 | +``` |
| 12 | + |
| 13 | +## Usage |
| 14 | + |
| 15 | +This gem provides a low-level implementation of the HTTP/2 protocol. It is designed to be used in conjunction with other libraries to provide a complete HTTP/2 client or server. However, it is straight forward to give examples of how to use the library directly. |
| 16 | + |
| 17 | +### Client |
| 18 | + |
| 19 | +Here is a basic HTTP/2 client: |
| 20 | + |
| 21 | +``` ruby |
| 22 | +require 'async' |
| 23 | +require 'async/io/stream' |
| 24 | +require 'async/http/endpoint' |
| 25 | +require 'protocol/http2/client' |
| 26 | + |
| 27 | +Async do |
| 28 | + endpoint = Async::HTTP::Endpoint.parse("https://www.google.com/search?q=kittens") |
| 29 | + |
| 30 | + peer = endpoint.connect |
| 31 | + |
| 32 | + puts "Connected to #{peer.inspect}" |
| 33 | + |
| 34 | + # IO Buffering: |
| 35 | + stream = Async::IO::Stream.new(peer) |
| 36 | + |
| 37 | + framer = Protocol::HTTP2::Framer.new(stream) |
| 38 | + client = Protocol::HTTP2::Client.new(framer) |
| 39 | + |
| 40 | + puts "Sending connection preface..." |
| 41 | + client.send_connection_preface |
| 42 | + |
| 43 | + puts "Creating stream..." |
| 44 | + stream = client.create_stream |
| 45 | + |
| 46 | + headers = [ |
| 47 | + [":scheme", endpoint.scheme], |
| 48 | + [":method", "GET"], |
| 49 | + [":authority", "www.google.com"], |
| 50 | + [":path", endpoint.path], |
| 51 | + ["accept", "*/*"], |
| 52 | + ] |
| 53 | + |
| 54 | + puts "Sending request on stream id=#{stream.id} state=#{stream.state}..." |
| 55 | + stream.send_headers(headers, Protocol::HTTP2::END_STREAM) |
| 56 | + |
| 57 | + puts "Waiting for response..." |
| 58 | + $count = 0 |
| 59 | + |
| 60 | + def stream.process_headers(frame) |
| 61 | + headers = super |
| 62 | + puts "Got response headers: #{headers} (#{frame.end_stream?})" |
| 63 | + end |
| 64 | + |
| 65 | + def stream.receive_data(frame) |
| 66 | + data = super |
| 67 | + |
| 68 | + $count += data.scan(/kittens/).count |
| 69 | + |
| 70 | + puts "Got response data: #{data.bytesize}" |
| 71 | + end |
| 72 | + |
| 73 | + until stream.closed? |
| 74 | + frame = client.read_frame |
| 75 | + end |
| 76 | + |
| 77 | + puts "Got #{$count} kittens!" |
| 78 | + |
| 79 | + puts "Closing client..." |
| 80 | + client.close |
| 81 | +end |
| 82 | +``` |
0 commit comments