create a http server with a custom route in rust

To create a simple HTTP server with a custom route in Rust, we can use the Hyper crate. First, add the following dependency to your Cargo.toml file:

[dependencies]
hyper = "0.14.8"
32 chars
3 lines

Then, in your main Rust file, you can create a basic HTTP server with the following code:

main.rs
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use std::convert::Infallible;

async fn handle_request(_: Request<Body>) -> Result<Response<Body>, Infallible> {
    Ok(Response::new(Body::from("Hello, World!")))
}

#[tokio::main]
async fn main() {
    let make_svc = make_service_fn(|_conn| async {
        Ok::<_, Infallible>(service_fn(handle_request))
    });
    let addr = ([127, 0, 0, 1], 3000).into();
    let server = Server::bind(&addr).serve(make_svc);
    println!("Listening on http://{}", addr);
    server.await.unwrap();
}
587 chars
19 lines

In this example, we're creating a simple HTTP server that responds to all incoming requests with the message "Hello, World!". Now, let's add a custom route.

main.rs
async fn handle_request(req: Request<Body>) -> Result<Response<Body>, Infallible> {
    match (req.method(), req.uri().path()) {
        (&Method::GET, "/") => {
            Ok(Response::new(Body::from("Hello, World!")))
        },
        (&Method::GET, "/custom_route") => {
            Ok(Response::new(Body::from("This is the custom route!")))
        },
        _ => {
            let response = Response::builder()
                .status(StatusCode::NOT_FOUND)
                .body(Body::empty())
                .unwrap();
            Ok(response)
        }
    }
}
575 chars
18 lines

Here, we're pattern matching on the incoming request method and URI path to determine which handler to call. In this example, we've added a custom route at /custom_route that responds with a different message.

With this addition to our handle_request function, we now have a custom route that will respond to GET requests at /custom_route.

gistlibby LogSnag