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

Here's an example of how to create an HTTP server in Rust using the hyper library and read the request body as bytes and return a binary response:

main.rs
use hyper::{Body, Request, Response, Server};
use hyper::rt::Future;
use hyper::service::service_fn_ok;

fn main() {
    let addr = ([127, 0, 0, 1], 3000).into();

    let new_service = || {
        service_fn_ok(move |req: Request<Body>| {
            let body = req.into_body();
            let bytes = hyper::rt::lazy(move || {
                body.concat2().map(|chunk| {
                    // This is the request body as bytes
                    let body_bytes = chunk.into_bytes();

                    // Create a binary response
                    let response = Response::builder()
                        .header("Content-Type", "application/octet-stream")
                        .body(Body::from(vec![0x01, 0x02, 0x03]))
                        .unwrap();

                    response
                })
            });

            bytes
        })
    };

    let server = Server::bind(&addr)
        .serve(new_service)
        .map_err(|e| eprintln!("server error: {}", e));

    hyper::rt::run(server);
}
1026 chars
36 lines

In this example, we define a closure new_service that takes a Request and returns a Response. Inside this closure, we first extract the request body as bytes using the concat2 method. We then create a new Response object containing our binary response, with the content type set to application/octet-stream.

We use the hyper library's Server::bind method to start the server, passing in our closure as the service that will handle incoming requests.

Note that for more complex applications, you may want to use a different approach for handling the request body, such as streaming the bytes as they come in using a tokio::codec.

gistlibby LogSnag