diff --git a/src/main.rs b/src/main.rs index b81917b..69944fd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,9 @@ #[macro_use] extern crate rocket; use rocket::{serde::{Deserialize, json::Json}, State, http::Status}; +use rocket::http::Header; +use rocket::{Request, Response}; +use rocket::fairing::{Fairing, Info, Kind}; use serde_json::json; use std::sync::RwLock; @@ -28,13 +31,13 @@ fn index() -> &'static str { } #[derive(Debug, Deserialize)] -struct Request { +struct RequestParams { formats: Vec, ids: Vec, } -#[post("/get_url", data = "")] -async fn get_url(req: Json, state_data: &State>) -> (Status, String) { +#[post("/get_url", format = "json", data = "")] +async fn get_url(req: Json, state_data: &State>) -> (Status, String) { if req.formats.is_empty() { return (Status::BadRequest, "Format list cannot be empty".to_string()); } @@ -78,9 +81,34 @@ async fn get_url(req: Json, state_data: &State>) -> ( (Status::Ok, media_resp.text().await.unwrap()) } +#[options("/get_url")] +fn send_options() -> Status { + Status::Ok +} + +pub struct CORS; + +#[rocket::async_trait] +impl Fairing for CORS { + fn info(&self) -> Info { + Info { + name: "Add CORS headers to responses", + kind: Kind::Response + } + } + + async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) { + response.set_header(Header::new("Access-Control-Allow-Origin", "*")); + response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, OPTIONS")); + response.set_header(Header::new("Access-Control-Allow-Headers", "*")); + response.set_header(Header::new("Access-Control-Allow-Credentials", "true")); + } +} + #[launch] fn rocket() -> _ { rocket::build() .manage(RwLock::new(StateData { client: APIClient::new() })) - .mount("/", routes![index, get_url]) + .mount("/", routes![index, get_url, send_options]) + .attach(CORS) } \ No newline at end of file