Module: Oaf::HTTP::Server

Extended by:
Oaf, Server
Included in:
Server
Defined in:
lib/oaf/http/server.rb

Constant Summary

Constants included from Oaf

VERSION

Instance Method Summary collapse

Instance Method Details

#get_request_body(req) ⇒ Object

Safely retrieves the request body, and assumes an empty string if it cannot be retrieved. This helps get around a nasty exception in WEBrick.

Parameters:

req

A WEBrick::HTTPRequest object

Returns:

A string containing the request body



63
64
65
66
67
68
69
70
71
72
# File 'lib/oaf/http/server.rb', line 63

def get_request_body req
  if ['POST', 'PUT'].member? req.request_method
    begin
      result = req.body
    rescue WEBrick::HTTPStatus::LengthRequired
      result = ''  # needs to be in rescue for coverage
    end
  end
  result
end

#parse_response(output) ⇒ Object

Given output from a script, parse HTTP response details and return them as a hash, including body, status, and headers.

Parameters:

output

The output text data returned by a script.

Returns:

A hash containing the HTTP response details (body, status, and headers).



43
44
45
46
47
48
49
50
51
# File 'lib/oaf/http/server.rb', line 43

def parse_response output
  has_meta = false
  headers = {'content-type' => 'text/plain'}
  status = 200
  headers, status, meta_size = Oaf::Util.parse_http_meta output
  lines = output.split("\n")
  body = lines.take(lines.length - meta_size).join("\n")+"\n"
  [headers, status, body]
end

#serve(path, port) ⇒ Object

Invokes the Webrick web server library to handle incoming requests, and routes them to the appropriate scripts if they exist on the filesystem.

Parameters:

path

The path in which to search for files

port

The TCP port to listen on



103
104
105
106
107
108
# File 'lib/oaf/http/server.rb', line 103

def serve path, port
  server = WEBrick::HTTPServer.new :Port => port
  server.mount '/', Oaf::HTTP::Handler, path
  trap 'INT' do server.shutdown end
  server.start
end

#set_response!(res, headers, body, status) ⇒ Object

Consume HTTP response details and set them into a response object.

Parameters:

res

A WEBrick::HTTPResponse object

headers

A hash containing HTTP response headers

body

A string containing the HTTP response body

status

An integer indicating the response status



86
87
88
89
90
91
92
# File 'lib/oaf/http/server.rb', line 86

def set_response! res, headers, body, status
  headers.each do |name, value|
    res.header[name] = value
  end
  res.body = body
  res.status = status
end