turul_http_mcp_server/
cors.rs1use hyper::HeaderMap;
4
5pub struct CorsLayer;
7
8impl CorsLayer {
9 pub fn apply_cors_headers(headers: &mut HeaderMap) {
11 headers.insert("Access-Control-Allow-Origin", "*".parse().unwrap());
12 headers.insert(
13 "Access-Control-Allow-Methods",
14 "GET, POST, OPTIONS".parse().unwrap(),
15 );
16 headers.insert(
17 "Access-Control-Allow-Headers",
18 "Content-Type, Accept, Authorization".parse().unwrap(),
19 );
20 headers.insert("Access-Control-Max-Age", "86400".parse().unwrap());
21 }
22
23 pub fn apply_cors_headers_for_origin(headers: &mut HeaderMap, origin: &str) {
25 headers.insert("Access-Control-Allow-Origin", origin.parse().unwrap());
26 headers.insert(
27 "Access-Control-Allow-Methods",
28 "GET, POST, OPTIONS".parse().unwrap(),
29 );
30 headers.insert(
31 "Access-Control-Allow-Headers",
32 "Content-Type, Accept, Authorization".parse().unwrap(),
33 );
34 headers.insert("Access-Control-Allow-Credentials", "true".parse().unwrap());
35 headers.insert("Access-Control-Max-Age", "86400".parse().unwrap());
36 }
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42
43 #[test]
44 fn test_apply_cors_headers() {
45 let mut headers = HeaderMap::new();
46 CorsLayer::apply_cors_headers(&mut headers);
47
48 assert_eq!(headers.get("Access-Control-Allow-Origin").unwrap(), "*");
49 assert!(headers.contains_key("Access-Control-Allow-Methods"));
50 assert!(headers.contains_key("Access-Control-Allow-Headers"));
51 assert!(headers.contains_key("Access-Control-Max-Age"));
52 }
53
54 #[test]
55 fn test_apply_cors_headers_for_origin() {
56 let mut headers = HeaderMap::new();
57 CorsLayer::apply_cors_headers_for_origin(&mut headers, "https://example.com");
58
59 assert_eq!(
60 headers.get("Access-Control-Allow-Origin").unwrap(),
61 "https://example.com"
62 );
63 assert_eq!(
64 headers.get("Access-Control-Allow-Credentials").unwrap(),
65 "true"
66 );
67 }
68}