added CORS shit

This commit is contained in:
uh wot 2021-09-15 14:03:08 +02:00
parent 00314ceeca
commit 640a720810
Signed by: uhwot
GPG Key ID: CB2454984587B781
1 changed files with 32 additions and 4 deletions

View File

@ -1,6 +1,9 @@
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket;
use rocket::{serde::{Deserialize, json::Json}, State, http::Status}; 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 serde_json::json;
use std::sync::RwLock; use std::sync::RwLock;
@ -28,13 +31,13 @@ fn index() -> &'static str {
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct Request { struct RequestParams {
formats: Vec<Format>, formats: Vec<Format>,
ids: Vec<u32>, ids: Vec<u32>,
} }
#[post("/get_url", data = "<req>")] #[post("/get_url", format = "json", data = "<req>")]
async fn get_url(req: Json<Request>, state_data: &State<RwLock<StateData>>) -> (Status, String) { async fn get_url(req: Json<RequestParams>, state_data: &State<RwLock<StateData>>) -> (Status, String) {
if req.formats.is_empty() { if req.formats.is_empty() {
return (Status::BadRequest, "Format list cannot be empty".to_string()); return (Status::BadRequest, "Format list cannot be empty".to_string());
} }
@ -78,9 +81,34 @@ async fn get_url(req: Json<Request>, state_data: &State<RwLock<StateData>>) -> (
(Status::Ok, media_resp.text().await.unwrap()) (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] #[launch]
fn rocket() -> _ { fn rocket() -> _ {
rocket::build() rocket::build()
.manage(RwLock::new(StateData { client: APIClient::new() })) .manage(RwLock::new(StateData { client: APIClient::new() }))
.mount("/", routes![index, get_url]) .mount("/", routes![index, get_url, send_options])
.attach(CORS)
} }