create a http server with a options route in rust

Here is an example of how to create an HTTP server with an OPTIONS route using Rust's Hyper crate:

main.rs
use hyper::{Body, Method, Request, Response, Server, StatusCode, header};
use std::net::SocketAddr;

async fn handle_request(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    match (req.method(), req.uri().path()) {
        (&Method::OPTIONS, "/options") => {
            let mut res = Response::new(Body::empty());
            res.headers_mut().insert(header::ALLOW, "OPTIONS, GET, POST".parse().unwrap());
            Ok(res)
        }
        _ => {
            let res = Response::builder()
                .status(StatusCode::NOT_FOUND)
                .body(Body::empty())
                .unwrap();
            Ok(res)
        }
    }
}

#[tokio::main]
async fn main() {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    let server = Server::bind(&addr).serve(|| {
        async { Ok::<_, hyper::Error>(hyper::service::make_service_fn(|_| async {
            Ok::<_, hyper::Error>(hyper::service::service_fn(handle_request))
        })) }
    });

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}
1067 chars
34 lines

In this example, we define a single route at the path "/options" that responds to OPTIONS requests with an empty body and the "ALLOW" header set to "OPTIONS, GET, POST".

Any other request will result in a 404 response.

The server is bound to localhost on port 3000 and runs indefinitely until manually terminated.

related categories

gistlibby LogSnag