create a http server and read the request body as form url encoded in rust

To create an HTTP server in Rust and read the request body as form url encoded, we can use the Hyper crate. Here's an example code snippet:

main.rs
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use std::convert::Infallible;
use futures::TryStreamExt;

async fn handle_request(req: Request<Body>) -> Result<Response<Body>, Infallible> {
    match (req.method(), req.uri().path()) {
        (&Method::POST, "/form") => {
            // Read the request body as form url encoded
            let body = req.into_body();
            let bytes = hyper::body::to_bytes(body).await.unwrap();
            let form = url::form_urlencoded::parse(&bytes);

            // Do something with the form data, e.g. print it to console
            for (key, value) in form {
                println!("{}={}", key, value);
            }

            // Return a response
            let response = Response::builder()
                .status(StatusCode::OK)
                .body(Body::empty())
                .unwrap();
            Ok(response)
        }
        _ => {
            let response = Response::builder()
                .status(StatusCode::NOT_FOUND)
                .body(Body::empty())
                .unwrap();
            Ok(response)
        }
    }
}

#[tokio::main]
async fn main() {
    let addr = ([127, 0, 0, 1], 3000).into();
    let server = Server::bind(&addr).serve(|| {
        async {
            Ok::<_, Infallible>(hyper::service::make_service_fn(|_conn| async {
                Ok::<_, Infallible>(hyper::service::service_fn(handle_request))
            }))
        }
    });

    println!("Listening on http://{}", addr);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}
1597 chars
52 lines

In this example code, we create a new HTTP server using the hyper::Server::bind() method. We define a handle_request() function which takes in a hyper::Request as input and returns a hyper::Response as output.

Inside handle_request(), we first check if the request method is POST and the request path is /form. If so, we read the request body as bytes using the hyper::body::to_bytes() method and parse it as a form url encoded using the url::form_urlencoded::parse() method.

Afterwards, we can do something with the form data, e.g. print it to console. Finally, we return a response with status code 200 OK and an empty body.

If the request method or path does not match, we return a 404 Not Found response.

Note that this example code uses the tokio runtime for asynchronous programming. We also need to include hyper, futures, and url as dependencies in Cargo.toml.

gistlibby LogSnag