Class: EventMachine::HttpServer::Server

Inherits:
EM::P::HeaderAndContentProtocol
  • Object
show all
Defined in:
lib/em-http-server/server.rb

Instance Method Summary collapse

Instance Method Details

#bad_parsingObject



56
57
58
59
60
61
62
# File 'lib/em-http-server/server.rb', line 56

def bad_parsing
  code = 400
  desc = "Bad request"
  string = respond_to?(:http_error_string) ? http_error_string(code, desc) : default_error_string(code, desc)
  send_error string
  raise("#{code} #{desc}")
end

#default_error_string(code, desc) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/em-http-server/server.rb', line 64

def default_error_string(code, desc)
  string = "HTTP/1.1 #{code} #{desc}\r\n"
  string << "Connection: close\r\n"
  string << "Content-type: text/plain\r\n"
  string << "\r\n"
  string << "Detected error: HTTP code #{code}"
end

#parse_first_header(line) ⇒ Object

parse the first HTTP header line get the http METHOD, URI and PROTOCOL



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/em-http-server/server.rb', line 41

def parse_first_header(line)

  # split the line into:  METHOD URI PROTOCOL
  # eg:  GET / HTTP/1.1
  parsed = line.split(' ')

  # a correct request has three parts
  return bad_parsing unless parsed.size == 3

  @http_request_method, uri, @http_protocol = parsed

  # optional query string
  @http_request_uri, @http_query_string = uri.split('?')
end

#receive_request(headers, content) ⇒ Object

everything starts from here. Protocol::HeaderAndContentProtocol does the dirty job for us it will pass headers and content, we just need to parse the headers the fill the right variables



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
# File 'lib/em-http-server/server.rb', line 12

def receive_request(headers, content)

  # save the whole headers array, verbatim
  @http_headers = headers

  # parse the headers into an hash to be able to access them like:
  #  @http[:host]
  #  @http[:content_type]
  @http = headers_2_hash headers

  # parse the HTTP request
  parse_first_header headers.first

  # save the binary content
  @http_content = content

  # invoke the method in the user-provided instance
  if respond_to?(:process_http_request)
    process_http_request
  end
rescue Exception => e
  # invoke the method in the user-provided instance
  if respond_to?(:http_request_errback)
    http_request_errback e
  end
end

#send_error(string) ⇒ Object

send back to the client an HTTP error



73
74
75
76
# File 'lib/em-http-server/server.rb', line 73

def send_error(string)
  send_data string
  close_connection_after_writing
end