Handling http request with variable parameters

In the building web example in the book we have these 2 lines for illustration:

    let get = b"GET / HTTP/1.1\r\n";
    let sleep = b"GET /sleep HTTP/1.1\r\n";

What if I wanted to get variable parameter like:

let book =  b"GET /book/<country>/<category> HTTP/1.1\r\n";

Where <country> and <category> are variable depending on what the user enter.

I know there are frameworks that do this for me, but interested in understanding it without using other crate.

You could do something like this, but there are likely lots of edge cases it doesn’t handle well: (Playground)

    // previously extracted from request
    let status_line = "GET /book/us/biography HTTP/1.1";

    match *(status_line.split_whitespace().collect::<Vec<_>>()) {
        ["GET", path, "HTTP/1.1"] => match *(path.split("/").collect::<Vec<_>>()){
            ["", "book", country, category] => {
                println!("Country: {}", country);
                println!("Category: {}", category);
            },
            _ => panic!("404 Not Found")
        },
        _ => panic!("Unsupported request")
    }
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.