add cors headers to a http server in rust

To add CORS headers to a Rust HTTP server, we can use the cors crate. Here's an example of how to add CORS headers to a simple HTTP server:

main.rs
use std::net::TcpListener;
use std::io::{Read, Write};
use cors::Cors;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

    // Wrap the server in a CORS middleware
    let cors = Cors::new()
        .allowed_origin("http://localhost:3000")
        .allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
        .allowed_headers(vec!["Authorization", "Content-Type"])
        .max_age(3600);

    for stream in listener.incoming() {
        match stream {
            Ok(mut stream) => {
                // Handle the request
                let mut buffer = [0; 1024];
                stream.read(&mut buffer).unwrap();

                let response = "HTTP/1.1 200 OK\r\n\r\nHello, world!";
                stream.write(response.as_bytes()).unwrap();
                stream.flush().unwrap();
            }
            Err(e) => println!("Error: {}", e),
        }
    }
}
903 chars
30 lines

In this example, we create a TcpListener and wrap it in a Cors middleware with the desired CORS configuration. We then handle incoming connections and use the cors middleware to add the appropriate CORS headers to the response.

related categories

gistlibby LogSnag