Leastrio
Leastrio

Reputation: 228

How can I get httparse to parse my request correctly?

Ive got an api set up by using a TcpListener, and when trying to parse the headers from the request data with httparse it only returns Err(HeaderName). I have also checked and I can confirm with printing the request data that I get a full request.

fn main() {
    let listener = TcpListener::bind("127.0.0.1:2352").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();

    let mut headers = [httparse::EMPTY_HEADER; 4];
    let parsed_headers = httparse::parse_headers(&buffer, &mut headers);

    let response = "HTTP/1.1 200 OK\r\n\r\n";

    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
    println!("Request Headers: {:?}", parsed_headers);
}

Upvotes: 1

Views: 3312

Answers (1)

Take-Some-Bytes
Take-Some-Bytes

Reputation: 952

The problem is that httparse::parse_headers() only parses HTTP headers, not the full HTTP request. It expects that the buffer you pass in only contains headers and the body. In other words, the parse_headers() function expects something like this:

Header1: Value1
Header2: Value2
Header3: Value3

This is the body.

But a full HTTP request looks something like this:

GET / HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3

That's what trips it up.

To parse a full request, you should use the httparse::Request struct, like so:

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();

    let mut headers = [httparse::EMPTY_HEADER; 4];
    let mut req = httparse::Request::new(&mut headers);
    let res = req.parse(&buffer).unwrap();

    // Here, ``res`` is an Err() if something went wrong, and Ok otherwise.
    // The ``req`` variable contains the request properties, and
    // the ``headers`` variable contains the headers.
}

Upvotes: 1

Related Questions