Skip to content

Commit

Permalink
use a case-insenstive header hash for upgrade server (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
kenichi authored and igrigorik committed Oct 27, 2016
1 parent 7ab50f5 commit 0ab8173
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions example/upgrade_server.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literals: true

require_relative 'helper'
require 'http_parser'
require 'base64'
Expand Down Expand Up @@ -27,6 +29,15 @@
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).freeze
UPGRADE_RESPONSE = <<-RESP
Expand All @@ -41,6 +52,7 @@ class UpgradeHandler
def initialize(conn, sock)
@conn, @sock = conn, sock
@complete, @parsing = false, false
@headers = request_header_hash
@body = ''
@parser = ::HTTP::Parser.new(self)
end
Expand Down Expand Up @@ -68,7 +80,7 @@ def complete!
end

def on_headers_complete(headers)
@headers = headers
@headers.merge! headers
end

def on_body(chunk)
Expand Down Expand Up @@ -100,15 +112,16 @@ def on_message_complete

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

Expand All @@ -122,9 +135,7 @@ def on_message_complete

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',
Expand Down

0 comments on commit 0ab8173

Please sign in to comment.