parser/parser.rs
1#![allow(unused_variables)]
2
3extern crate http_muncher;
4use std::str;
5
6// Include the 2 main public interfaces of the crate
7use http_muncher::{Parser, ParserHandler};
8
9// Now let's define a new listener for parser events:
10struct MyHandler;
11
12impl ParserHandler for MyHandler {
13
14 // Now we can define our callbacks here.
15 //
16 // Let's try to handle headers: the following callback function will be
17 // called when parser founds a header chunk in the HTTP stream.
18 fn on_header_field(&mut self, parser: &mut Parser, header: &[u8]) -> bool {
19 // Print the received header key part
20 println!("{}: ", str::from_utf8(header).unwrap());
21
22 // We have nothing to say to parser, and we'd like
23 // it to continue its work - so let's return "true".
24 true
25 }
26
27 // And let's print the header value chunks in a similar vein:
28 fn on_header_value(&mut self, parser: &mut Parser, value: &[u8]) -> bool {
29 println!("\t{}", str::from_utf8(value).unwrap());
30 true
31 }
32
33
34
35}
36
37fn main() {
38 // Now we can create a parser instance with our callbacks handler:
39 let mut callbacks_handler = MyHandler {};
40 let mut parser = Parser::request();
41
42 // Let's define a mock HTTP request:
43 let http_request = "GET / HTTP/1.1\r\n\
44 Content-Type: text/plain\r\n\
45 Content-Length: 2\r\n\
46 Hello: World\r\n\r\n\
47 Hi";
48
49 // And now we're ready to go!
50 parser.parse(&mut callbacks_handler, http_request.as_bytes());
51
52 // Now that callbacks have been called, we can introspect
53 // the parsing results. For instance, print the HTTP version:
54 let (http_major, http_minor) = parser.http_version();
55 println!("\nHTTP v.{}.{}", http_major, http_minor);
56}
57
58// Now execute "cargo run", and as a result you should see this output:
59
60// Content-Type:
61// text/plain
62// Content-Length:
63// 0
64// Hello:
65// World
66//
67// HTTP v1.1
68
69// ... and the rest is almost the same - have fun experimenting!