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

To create an HTTP server in Rust, we can use the hyper crate, which provides a powerful and easy-to-use HTTP library. Here is an example of creating an HTTP server with hyper that reads the request body as binary:

main.rs
use hyper::{Body, Request, Response, Server};
use bytes::Buf;

async fn handle_request(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    let body_bytes = hyper::body::to_bytes(req.into_body()).await?;
    // Now `body_bytes` is a `Bytes` object, which can be converted to a `Vec<u8>`
    let binary_data = body_bytes.to_vec();
    Ok(Response::new("Received binary data!".into()))
}

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

    println!("Listening on http://{}", addr);
    if let Err(e) = service.await {
        eprintln!("server error: {}", e);
    }
}
915 chars
29 lines

In this example, we define an async function handle_request that takes a Request object, reads the request body bytes as a Bytes object using hyper::body::to_bytes, and then converts the Bytes object to a vector of bytes using the to_vec method. Finally, we create a Response object that sends a simple message indicating that binary data was received.

We then define the main function that creates an instance of the Server object, binds it to a specific address, and then starts the server by calling its serve method. The server uses a make_service_fn to create the service that will be used to handle incoming requests by calling handle_request.

When run, this program will start an HTTP server that listens on port 3000 and prints a message to the console indicating the address it is listening on.

Note: make sure to include the hyper and bytes crates in your project dependencies in order to use this code.

gistlibby LogSnag