Module: HTTPHandler

Defined in:
lib/wdd-ruby-ext/utils/test_server.rb

Instance Method Summary collapse

Instance Method Details

#extract_query_params(query) ⇒ Object



13
14
15
16
17
# File 'lib/wdd-ruby-ext/utils/test_server.rb', line 13

def extract_query_params( query )
  query = CGI::unescape( query )
  pairs = query.split("&")
  pairs.inject({}){|hash, pair| k,v=pair.split('='); v.nil? ? hash : (hash[k.to_sym]=v;hash)}
end

#http_request?(data) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/wdd-ruby-ext/utils/test_server.rb', line 19

def http_request? data
  http_request = nil
  matches = data.split("\n").first.match(/(\w*) ([^\?]*)\??([^#]*)#?(.*) HTTP\/1\.1/)
  if matches
    http_request = {}
    http_request[:request] = matches[0]
    captures = matches.captures
    http_request[:command] = captures.shift
    http_request[:path] = captures.shift
    http_request[:query_params] = extract_query_params(captures.shift)
    http_request[:anchor] = captures.shift
  end
  # pp http_request
  http_request
end

#http_response(return_data, code = 200) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'lib/wdd-ruby-ext/utils/test_server.rb', line 48

def http_response( return_data, code=200 )
  headers = <<-TXT
HTTP/1.1 #{ code } OK 
Connection: Keep-Alive
Content-Type: text/html; charset=utf-8

TXT
  headers + return_data
end

#process_http_request(http_request) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/wdd-ruby-ext/utils/test_server.rb', line 35

def process_http_request( http_request )
  if sleep_time = http_request[:query_params][:sleep]
    sleep( sleep_time.to_i )
  end
  if sleep_time = http_request[:query_params][:random_sleep]
    sleep( rand(sleep_time.to_i * 1000).to_f/1000)
  end
  unless return_data = http_request[:query_params][:return_data]
    return_data = "Your HTTP Request(#{http_request[:request]}) was processed by the TestServer."
  end
  http_response(return_data)
end