Module: Chase::HttpParser

Included in:
Server
Defined in:
lib/chase/http_parser.rb

Overview

Handle parsing of incoming http requests

Constant Summary collapse

VALID_METHODS =
%w(GET POST PUT DELETE PATCH HEAD OPTIONS).freeze
MAPPED_HEADERS =
{ 'cookie' => 'HTTP_COOKIE', 'if-none-match' => 'IF_NONE_MATCH',
'content-type' => 'CONTENT_TYPE', 'content-length' => 'CONTENT_LENGTH' }.freeze

Instance Method Summary collapse

Instance Method Details

#http_methodObject



49
50
51
# File 'lib/chase/http_parser.rb', line 49

def http_method
  http_parser.http_method
end

#http_parserObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/chase/http_parser.rb', line 10

def http_parser
  @parser ||= HTTP::Parser.new.tap do |parser|
    parser.on_headers_complete { @current_header = nil }

    parser.on_url do |url|
      raise HTTP::Parser::Error, 'Invalid method' unless VALID_METHODS.include?(http_method)

      set_env('REQUEST_METHOD', http_method)
      set_env('REQUEST_URI', url)
      matches = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/)
      matches ||= Hash.new('')
      set_env('PROTOCOL', matches[2])
      set_env('PATH_INFO', matches[5])
      set_env('QUERY_STRING', matches[7])
    end

    parser.on_header_field { |name| @current_header = name }

    parser.on_header_value do |value|
      if key = MAPPED_HEADERS[@current_header.downcase]
        set_env(key, value)
      else
        request.headers[@current_header] = value
      end
    end

    parser.on_body { |body| set_env('POST_CONTENT', body) }

    parser.on_message_begin do
      set_env('HTTP_COOKIE', '')
      set_env('POST_CONTENT', '')
    end

    parser.on_message_complete do
      request.emit(:created)
    end
  end
end

#set_env(key, value) ⇒ Object



53
54
55
# File 'lib/chase/http_parser.rb', line 53

def set_env(key, value)
  request.env[key] = value
end