Technology Agnostic Rubyist : Open Source Lights The Way

Friday, June 21, 2013

Two line HTTP Server with Rack

Working APIs often has its own set of challenges. One of these that I've come across often enough to blog about is composing an initial request to the API and tracking down errors.

To test if the problem arises from a malformed querystring or the http header, I needed to mock the http_request and echo the http_response.

To compose an HTTP requests I like to use the CURL library.

To echo the full HTTP request back to the requester, I wrote a simple two line HTTP Server.
require 'rack'
echo = lambda { |env| [200, {}, env.map{|k,v|"#{k}:\t#{v}\n"} ] }

To run the server, simply fire up an IRB console and copy/paste the code above and type.
Rack::Server.start :app => echo, :Port => 8080

That's it, you're ready to see it in action! curl an HTTP request.
curl -v http://localhost:8080/show_me_the_money?in_small_unmarked_bills=100bills

And you'll get a full echo of the HTTP request.
* About to connect() to localhost port 8080 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET /show_me_the_money?in_small_unmarked_bills=100bills HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:8080
> Accept: */*

< HTTP/1.1 200 OK 
< Server: WEBrick/1.3.1 (Ruby/1.9.3/2013-05-15)
< Date: Fri, 21 Jun 2013 14:22:32 GMT
< Content-Length: 703
< Connection: Keep-Alive

GATEWAY_INTERFACE: CGI/1.1
PATH_INFO: /show_me_the_money
QUERY_STRING: in_small_unmarked_bills=100bills
REMOTE_ADDR: ::1
REMOTE_HOST: localhost
REQUEST_METHOD: GET
REQUEST_URI: http://localhost:8080/show_me_the_money?in_small_unmarked_bills=100bills
SCRIPT_NAME:
SERVER_NAME: localhost
SERVER_PORT: 8080
SERVER_PROTOCOL: HTTP/1.1
SERVER_SOFTWARE: WEBrick/1.3.1 (Ruby/1.9.3/2013-05-15)
HTTP_USER_AGENT: curl/7.29.0
HTTP_HOST: localhost:8080
HTTP_ACCEPT: */*
rack.version: [1, 1]
rack.input: #<StringIO:0x007f84131738d0>
rack.errors: #<IO:0x007f841306f420>
rack.multithread: true
rack.multiprocess: false
rack.run_once: false
rack.url_scheme: http
HTTP_VERSION: HTTP/1.1

REQUEST_PATH: /show_me_the_money

Tweets

Contributors