add cors headers to a http server with a specific origin and methods in rust

To add CORS headers to a HTTP server with a specific origin and methods in Rust, we can use the cors crate. Here's an example:

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

async fn handle_request(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
  let method = req.method();
  let response = match method {
    &Method::GET => Response::new(Body::from("You invoked a GET method.")),
    &Method::POST => Response::new(Body::from("You invoked a POST method.")),
    _ => {
      let mut not_supported = Response::default();
      *not_supported.status_mut() = StatusCode::METHOD_NOT_ALLOWED;
      not_supported
    }
  };
  Ok(response)
}

#[tokio::main]
async fn main() {
  let addr = SocketAddr::from(([127, 0, 0, 1], 3000));

  let allowed_origin = Cors::new()
    .allowed_origin("http://localhost:8080")
    .allowed_methods(vec!["GET", "POST"])
    .allow_credentials(true);

  let make_svc = hyper::service::make_service_fn(move |_| {
    let allowed_origin = allowed_origin.clone();
    async move {
      Ok::<_, hyper::Error>(allowed_origin.handle(
        hyper::service::service_fn(handle_request)
      ))
    }
  });

  let server = Server::bind(&addr)
    .serve(make_svc)
    .await
    .unwrap();

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

  server.await.unwrap();
}
1236 chars
46 lines

In this example, we've defined a handle_request function that returns a different response based on the HTTP method called (GET or POST). We then create a Cors instance with the allowed origin, methods, and credentials. Finally, we define a make_svc function that clones the Cors instance and returns a service function that handles incoming requests by passing them to handle_request and the Cors instance. We then bind and start the HTTP server with the serve method.

Using this code, the HTTP server will respond with the appropriate CORS headers, allowing requests from the specified origin and with the specified methods.

gistlibby LogSnag