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

To add CORS headers to a HTTP server with a specific origin in Rust, one can use the crate headers which provides an easy way to manipulate HTTP headers. Below is an example of how to add CORS headers to a HTTP server with the specific origin "example.com":

main.rs
use headers::{HeaderMap, HeaderValue, ACCESS_CONTROL_ALLOW_ORIGIN};

fn add_cors_headers(headers: &mut HeaderMap) {
    headers.insert(
        ACCESS_CONTROL_ALLOW_ORIGIN,
        HeaderValue::from_static("http://example.com")
    );
    // Add other CORS headers here as needed
}

// In your server code:
let mut response = http::Response::new(());
add_cors_headers(response.headers_mut());
393 chars
14 lines

In the example above, the add_cors_headers function takes a mutable reference to a HeaderMap and sets the Access-Control-Allow-Origin header to "http://example.com". Other CORS headers, such as Access-Control-Allow-Headers and Access-Control-Allow-Methods, can be added in a similar way as needed.

Note that adding CORS headers in this way is only one part of enabling CORS on a server. The server also needs to handle preflight requests and allow the appropriate methods and headers.

related categories

gistlibby LogSnag