1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use rocket::State;
use rocket::Response;
use rocket::Request;
use rocket::fairing::Info;
use rocket::fairing::Fairing;
use rocket::fairing::Kind;
use rocket::http::{Method,Header,ContentType};
use std::io::Cursor;
use log::{debug, error, log_enabled, info, Level};
#[derive(Debug)]
pub struct Origin{
pub origin:String
}
pub struct CORS;
impl Fairing for CORS {
fn info(&self) -> Info {
Info {
name: "Add CORS headers to requests",
kind: Kind::Response
}
}
fn on_response(&self, request: &Request, response: &mut Response) {
let app_config = request.guard::<State<Origin>>().unwrap();
let a = app_config.origin.clone();
if request.method() == Method::Options || response.content_type() == Some(ContentType::JSON) {
response.set_header(Header::new("Access-Control-Allow-Origin", a));
response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, OPTIONS"));
response.set_header(Header::new("Access-Control-Allow-Headers", "Content-Type"));
response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
}
if request.method() == Method::Options {
response.set_header(ContentType::Plain);
response.set_sized_body(Cursor::new(""));
response.set_status(rocket::http::Status::new(204, "No Content"));
}
}
}