create a http server with a post route in rust

To create an HTTP server with a POST route in Rust, you can use the hyper crate. Here's an example:

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

fn handle_post_request(req: Request<Body>) -> Response<Body> {
    // Handle POST request logic here
    Response::new(Body::from("Received POST request"))
}

fn main() {
    // Create a new server that listens on localhost:8080
    let addr = ([127, 0, 0, 1], 8080).into();

    // Create a closure to handle incoming requests
    let new_service = || {
        // Return a closure that handles incoming requests
        service_fn_ok(|req: Request<Body>| match (req.method(), req.uri().path()) {
            (&hyper::Method::POST, "/post") => handle_post_request(req),
            _ => Response::new(Body::from("404 Not Found")),
        })
    };

    // Create the server with the closure as the service
    let server = Server::bind(&addr)
        .serve(new_service)
        .map_err(|e| eprintln!("server error: {}", e));

    // Run the server
    hyper::rt::run(server);
}
987 chars
31 lines

This example creates a new HTTP server that listens on localhost:8080. When a POST request is received at the /post endpoint, the handle_post_request function is called. The response body for this example is a simple String that says "Received POST request".

related categories

gistlibby LogSnag