Skip to content

tmm1/http_parser.rb

This branch is 186 commits ahead of, 1 commit behind macournoyer/ruby_http_parser:master.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

7aeb7a2 · Mar 14, 2025
Mar 13, 2025
Mar 11, 2012
Sep 1, 2021
Apr 8, 2011
Sep 1, 2021
Feb 3, 2023
Jun 23, 2014
May 27, 2018
Apr 20, 2013
Mar 17, 2011
Dec 6, 2017
Sep 1, 2021
Aug 2, 2024

Repository files navigation

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 http-parser/http-parser.java.

Supported Platforms

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

  • MRI 1.8, 1.9 and 2.0; should work on MRI 2.4+
  • 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]

About

simple callback-based HTTP request/response parser

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Ruby 39.5%
  • Java 30.3%
  • C 30.2%