I would make use of WEBrick
. WEBrick::HTTPRequest
has a serviceable parser, and all you need to do is pass an IO
object to its parse
method and you have yourself an object you can manipulate.
This example declares a POST request with a JSON body in a string and uses StringIO
to make it accessible as an IO
object.
require 'webrick'
require 'stringio'
Request = <<-HTTP
POST /url/path HTTP/1.1
Host: my.hostname.com
Content-Type: application/json
Content-Length: 62
{
"firstName": "John",
"lastName": "Smith",
"age": 25
}
HTTP
req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
req.parse(StringIO.new(Request))
puts req.path
req.each { |head| puts "#{head}: #{req[head]}" }
puts req.body
output
/url/path
host: my.hostname.com
content-type: application/json
content-length: 62
{
"firstName": "John",
"lastName": "Smith",
"age": 25
}