Class: IrcMachine::HttpServer

Inherits:
EM::Connection
  • Object
show all
Includes:
EM::HttpServer
Defined in:
lib/irc_machine/http_server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#routerObject

Returns the value of attribute router.



9
10
11
# File 'lib/irc_machine/http_server.rb', line 9

def router
  @router
end

Instance Method Details

#headersObject



60
61
62
# File 'lib/irc_machine/http_server.rb', line 60

def headers
  @headers ||= parse_headers(@http_headers)
end

#parse_headers(header) ⇒ Object

ghetto



65
66
67
68
69
70
# File 'lib/irc_machine/http_server.rb', line 65

def parse_headers(header)
  header.split("\x00").inject({}) do |headers, line|
    headers[$1] = $2 if line =~ /^([^:]+):\s*(.*)$/
    headers
  end
end

#process_http_requestObject



11
12
13
14
15
16
17
# File 'lib/irc_machine/http_server.rb', line 11

def process_http_request
  send_response(*router.route(rack_env))
rescue => e
  puts "!! #{self.class} rescued #{e.inspect}"
  puts "    " + e.backtrace.join("\n    ")
  send_response 500, {}, [ e.inspect, "\n" ]
end

#rack_envObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/irc_machine/http_server.rb', line 29

def rack_env
  # TODO: map headers to HTTP_... keys.
  {
    "rack.version" => [1, 1],
    "rack.url_scheme" => @http_protocol,
    "rack.input" => StringIO.new((@http_post_content || "")),
    "rack.errors" => open("/dev/null", "w"), # muahaha
    "rack.multithread" => false,
    "rack.multiprocess" => false,
    "rack.run_once" => false,

    "REQUEST_METHOD" => @http_request_method,
    "SCRIPT_NAME" => "", # see PATH_INFO
    "PATH_INFO" => @http_path_info,
    "QUERY_STRING" => @http_query_string,
    "SERVER_NAME" => nil, # illegally nil
    "SERVER_PORT" => nil, # illegally nil
    "REMOTE_ADDR" => remote_ip, # not in spec

    "HTTP_COOKIE" => @http_cookie,
    "HTTP_IF_NONE_MATCH" => @http_if_none_match,
    "HTTP_CONTENT_TYPE" => @http_content_type,
    "HTTP_X_AUTH" => headers["X-Auth"],
  }
end

#remote_ipObject



55
56
57
58
# File 'lib/irc_machine/http_server.rb', line 55

def remote_ip
  port, ip = Socket.unpack_sockaddr_in(get_peername)
  ip
end

#send_response(status, headers, body) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/irc_machine/http_server.rb', line 19

def send_response(status, headers, body)
  EM::DelegatedHttpResponse.new(self).tap do |r|
    r.status = status
    r.headers = headers
    # Rack body is only guaranteed to respond to #each
    r.content = "".tap { |c| body.each { |b| c << b } }
    r.send_response
  end
end