create a http server with a delete route in rust

Here's an example code to create an HTTP server with a DELETE route in Rust using the hyper crate:

main.rs
extern crate hyper;

use hyper::{Body, Method, Request, Response, Server, StatusCode};
use hyper::rt::Future;
use hyper::service::service_fn_ok;

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

    let new_svc = || {
        service_fn_ok(move |req: Request<Body>| {
            match (req.method(), req.uri().path()) {
                (&Method::DELETE, "/delete") => {
                    // Handle DELETE request
                    Response::builder()
                        .status(StatusCode::OK)
                        .body(Body::from("Deleted successfully"))
                        .unwrap()
                },
                _ => {
                    // Return 404 Not Found for all other routes
                    Response::builder()
                        .status(StatusCode::NOT_FOUND)
                        .body(Body::from("Not Found"))
                        .unwrap()
                }
            }
        })
    };

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

    println!("Listening on http://{}", addr);

    hyper::rt::run(server);
}
1151 chars
39 lines

In this example, we define a new_svc function that returns a closure of type Fn(Request<Body>) -> Response<Body>. This closure matches the incoming request's method (DELETE) and path (/delete) and returns a successful 200 OK response with a body of "Deleted successfully" for the DELETE route. For all other routes, it returns a 404 Not Found response with a body of "Not Found".

We then use new_svc to initialize a Server instance and bind it to a specified address, in this case, 127.0.0.1:3000. Finally, we start the server with hyper::rt::run.

related categories

gistlibby LogSnag