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

To create a HTTP server and read the request body as text in Rust, you can use the hyper library. Here's an example code:

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 builder = Server::bind(&addr);

    let server = builder.serve(|| {
        service_fn_ok(handle_request)
    });

    let server = server.map_err(drop);
    hyper::rt::run(server);
}

fn handle_request(req: Request<Body>) -> Response<Body> {
    let body = req.into_body();

    let whole_body = body.concat2().wait().unwrap();
    let body_text = String::from_utf8(whole_body.to_vec()).unwrap();

    Response::new(Body::from(body_text))
}
613 chars
25 lines

In this code, we first create a Server instance and bind it to the address 127.0.0.1:3000. We then use a closure to define the service function that handles HTTP requests. The handle_request function is called for each incoming request, and it reads the entire request body into a vector using the concat2 method. We then convert the vector to a UTF-8 string and create a new response with the same text as the request body.

Finally, we start the server with hyper::rt::run(server). This starts the event loop and runs the server until it is closed.

Note that in a real-world HTTP server implementation, you would need to handle errors, set response headers, and handle different HTTP methods and paths.

related categories

gistlibby LogSnag