create a http server and read the request body as multipart form data in rust

To create an HTTP server and read the request body as multipart form data in Rust, you can use the hyper and multipart crates.

Here is an example code snippet:

main.rs
use hyper::{Body, Request, Response, Server};
use hyper::{header, StatusCode};
use hyper::service::{make_service_fn, service_fn};
use futures_util::StreamExt;
use std::convert::Infallible;

async fn handle_request(req: Request<Body>) -> Result<Response<Body>, Infallible> {
    // Check if the request method is POST:
    if req.method() != hyper::Method::POST {
        return Ok(Response::builder()
            .status(StatusCode::METHOD_NOT_ALLOWED)
            .body(Body::empty())
            .unwrap());
    }
    
    // Parse the multipart form data:
    let boundary = req.headers()
        .get(header::CONTENT_TYPE)
        .and_then(|ct| ct.to_str().ok())
        .and_then(|ct| ct.split(';').nth(1))
        .and_then(|s| s.trim().strip_prefix("boundary=").map(|s| s.to_string()));
    
    let multipart = match boundary {
        Some(b) => hyper::body::to_bytes(req.into_body())
            .await
            .map(|buf| multipart::server::Multipart::with_body(buf.as_ref(), b)),
        None => Err("Content-Type header invalid or missing".to_owned())
    }?;

    // Iterate over the parts of the multipart form data:
    while let Some(part) = multipart.next_field().await.unwrap() {
        // Do something with each part of the multipart form data:
        println!("Field name: {}", part.name());
        println!("Field value: {:?}", part.text().await.unwrap());
    }
    
    Ok(Response::new(Body::from("Success!")))
}

#[tokio::main]
async fn main() {
    let addr = ([127, 0, 0, 1], 3000).into();
    let make_svc = make_service_fn(|_conn| async {
        Ok::<_, Infallible>(service_fn(handle_request))
    });
    let server = Server::bind(&addr).serve(make_svc);
    println!("Listening on http://{}", addr);
    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}
1825 chars
52 lines

This code creates an HTTP server at http://127.0.0.1:3000, and listens for POST requests containing multipart form data. Upon receiving a request, the code parses the multipart form data and iterates over its parts, printing the name and value of each field to the console. The code then responds with a 200 OK status code and a success message.

gistlibby LogSnag