blob: e29ef2c6613d32b1805966de8f0222571c2a4b82 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
# 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](https://github.com/joyent/http-parser) and its java port [http-parser/http-parser.java](https://github.com/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
```ruby
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
```ruby
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
```ruby
parser = Http::Parser.new
parser.on_headers_complete = proc{ :stop }
offset = parser << request_data
body = request_data[offset..-1]
```
|