example/upgrade_server.rb in http-2-0.8.2 vs example/upgrade_server.rb in http-2-0.8.3

- old
+ new

@@ -1,8 +1,9 @@ +# frozen_string_literals: true + require_relative 'helper' require 'http_parser' -require 'base64' options = { port: 8080 } OptionParser.new do |opts| opts.banner = 'Usage: server.rb [options]' @@ -18,19 +19,28 @@ puts "Starting server on port #{options[:port]}" server = TCPServer.new(options[:port]) if options[:secure] ctx = OpenSSL::SSL::SSLContext.new - ctx.cert = OpenSSL::X509::Certificate.new(File.open('keys/mycert.pem')) - ctx.key = OpenSSL::PKey::RSA.new(File.open('keys/mykey.pem')) + ctx.cert = OpenSSL::X509::Certificate.new(File.open('keys/server.crt')) + ctx.key = OpenSSL::PKey::RSA.new(File.open('keys/server.key')) ctx.npn_protocols = [DRAFT] server = OpenSSL::SSL::SSLServer.new(server, ctx) end +def request_header_hash + Hash.new do |hash, key| + k = key.to_s.downcase + k.tr! '_', '-' + _, value = hash.find { |header_key, _| header_key.downcase == k } + hash[key] = value if value + end +end + class UpgradeHandler - VALID_UPGRADE_METHODS = %w(GET OPTIONS) + VALID_UPGRADE_METHODS = %w(GET OPTIONS).freeze UPGRADE_RESPONSE = <<-RESP HTTP/1.1 101 Switching Protocols Connection: Upgrade Upgrade: h2c @@ -39,10 +49,11 @@ attr_reader :complete, :headers, :body, :parsing def initialize(conn, sock) @conn, @sock = conn, sock @complete, @parsing = false, false + @headers = request_header_hash @body = '' @parser = ::HTTP::Parser.new(self) end def <<(data) @@ -66,11 +77,11 @@ def complete! @complete = true end def on_headers_complete(headers) - @headers = headers + @headers.merge! headers end def on_body(chunk) @body << chunk end @@ -98,19 +109,20 @@ puts "Received frame: #{frame.inspect}" end conn.on(:stream) do |stream| log = Logger.new(stream.id) - req, buffer = {}, '' + req = request_header_hash + buffer = '' stream.on(:active) { log.info 'client opened new stream' } stream.on(:close) do log.info 'stream closed' end stream.on(:headers) do |h| - req = Hash[*h.flatten] + req.merge! Hash[*h.flatten] log.info "request headers: #{h}" end stream.on(:data) do |d| log.info "payload chunk: <<#{d}>>" @@ -120,12 +132,10 @@ stream.on(:half_close) do log.info 'client closed its end of the stream' if req['Upgrade'] log.info "Processing h2c Upgrade request: #{req}" - - # Don't respond to OPTIONS... - if req[':method'] != 'OPTIONS' + if req[':method'] != 'OPTIONS' # Don't respond to OPTIONS... response = 'Hello h2c world!' stream.headers({ ':status' => '200', 'content-length' => response.bytesize.to_s, 'content-type' => 'text/plain',