create a http server and read the request body as html in rust

To create an HTTP server in Rust and read the request body as HTML, you can use the hyper and select crates. Here's an example code that demonstrates the process:

main.rs
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use hyper::header::CONTENT_TYPE;
use hyper::rt::Future;
use hyper::service::{make_service_fn, service_fn};
use select::document::Document;
use select::predicate::Name;

async fn handle_request(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    // Check if the request method is POST and the content type is HTML
    if req.method() == Method::POST {
        if let Some(ct) = req.headers().get(CONTENT_TYPE) {
            let content_type = ct.to_str().unwrap_or("");
            if content_type.starts_with("text/html") {
                // Read the request body and parse the HTML document
                let body = hyper::body::to_bytes(req.into_body()).await?;
                let html = String::from_utf8(body.to_vec()).unwrap_or_default();
                let doc = Document::from(html.as_str());
                if let Some(title) = doc.find(Name("title")).next() {
                    return Ok(Response::new(title.text().into()))
                }
            }
        }
    }

    // Return a 404 error for unrecognized requests
    let mut not_found = Response::default();
    *not_found.status_mut() = StatusCode::NOT_FOUND;
    Ok(not_found)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Bind the server to port 8080
    let addr = ([127, 0, 0, 1], 8080).into();

    // Use a closure to create a service for each incoming connection
    let make_svc = make_service_fn(|_conn| async {
        Ok::<_, hyper::Error>(service_fn(handle_request))
    });

    // Start the server
    let server = Server::bind(&addr).serve(make_svc);
    println!("Listening on http://{}", addr);
    server.await?;
    Ok(())
}
1757 chars
47 lines

This code defines an asynchronous function handle_request that receives a hyper Request and returns a Response. It checks if the request method is POST and the Content-Type header starts with "text/html". If so, it reads the request body, parses the HTML document using the select crate, and returns the <title> element as the response body. Otherwise, it returns a 404 error.

The main function binds the server to port 8080, creates a service for each incoming connection using the handle_request function, and starts the server. You can run this code with cargo run and send a POST request with HTML content to http://localhost:8080/ to test it.

gistlibby LogSnag