Getting a glimpse into Net::HTTP requests

February 16, 2008 code 2 min read

While trying to debug some HTTP code, I wanted to be able to see what the actual HTTP request looked before it was sent. So, I added a #to_s method:

require 'stringio'

class Net::HTTPGenericRequest
  def to_s
    io =
    exec(io, '1.1', path)

All the built in requests extend HTTPGenericRequest, so now I can call #to_s on any request:

request = request ='/some/path')
request.set_content_type 'text/html'
request.basic_auth 'username', 'password'

puts request.to_s

Which gives me:

GET /some/path HTTP/1.1
Accept: */*
Content-Type: text/html
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

I had also intended to add a #to_s method to the response, but it wasn’t obvious how to accomplish that, and I found my bug before I needed it. So, if anyone feels ambitious…

This content is open source. Suggest Improvements.


avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.