Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

simple callback-based HTTP request/response parser

branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 bench
Octocat-spinner-32 ext
Octocat-spinner-32 lib
Octocat-spinner-32 spec
Octocat-spinner-32 tasks
Octocat-spinner-32 .gitignore
Octocat-spinner-32 .gitmodules
Octocat-spinner-32 Gemfile
Octocat-spinner-32 Gemfile.lock
Octocat-spinner-32 LICENSE-MIT
Octocat-spinner-32 README.md
Octocat-spinner-32 Rakefile
Octocat-spinner-32 http_parser.rb.gemspec
README.md

http_parser.rb

A simple callback-based HTTP request/response parser for writing http servers, clients and proxies.

This gem is built on top of joyent/http-parser and its java port a2800276/http-parser.java.

Supported Platforms

This gem aims to work on all major Ruby platforms, including:

  • MRI 1.8 and 1.9
  • Rubinius
  • JRuby
  • win32

Usage

require "http/parser"

parser = Http::Parser.new

parser.on_headers_complete = proc do
  p parser.http_version

  p parser.http_method # for requests
  p parser.request_url

  p parser.status_code # for responses

  p parser.headers
end

parser.on_body = proc do |chunk|
  # One chunk of the body
  p chunk
end

parser.on_message_complete = proc do |env|
  # Headers and body is all parsed
  puts "Done!"
end

Feed raw data from the socket to the parser

parser << raw_data

Advanced Usage

Accept callbacks on an object

module MyHttpConnection
  def connection_completed
    @parser = Http::Parser.new(self)
  end

  def receive_data(data)
    @parser << data
  end

  def on_message_begin
    @headers = nil
    @body = ''
  end

  def on_headers_complete(headers)
    @headers = headers
  end

  def on_body(chunk)
    @body << chunk
  end

  def on_message_complete
    p [@headers, @body]
  end
end

Stop parsing after headers

parser = Http::Parser.new
parser.on_headers_complete = proc{ :stop }

offset = parser << request_data
body = request_data[offset..-1]
Something went wrong with that request. Please try again.