Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Parse (not get) an HTTP Request in Ruby

I have an integration test which uses eventmachine to receive http requests. This is my eventmachine handler:

class NotificationRecipient < EM::Connection
  def receive_data(data)
    EM.stop
  end
end

I need to test various properies of the received request, e.g. I want to extract a json payload from an HTTP POST request string I've received like this. Is there a nicely packaged way to do it?

Googling finds lots of ways to make a request and parse the response, e.g. rest-client will parse response automatically. However, since I'm receiving the request, not making it, none of these ways work for me.

like image 260
Stefan Avatar asked Jul 11 '13 13:07

Stefan


1 Answers

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
}
like image 175
Borodin Avatar answered Sep 28 '22 20:09

Borodin