Skip to content

Commit

Permalink
Merge pull request #21 from lexara-prime-ai/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
irfanghat authored May 31, 2024
2 parents ff2b2f8 + 82241f2 commit c89b4a6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ repository = "https://github.com/lexara-prime-ai/wspr_cdk"
readme = "README.md"
keywords = ["radio", "web", "http", "api"]
categories = ["web-programming::http-server", "science::geo"]
license = "MIT"
license = "BSD 3-Clause License"


# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
45 changes: 44 additions & 1 deletion wspr_cdk_server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@
#[macro_use]
extern crate rocket;

////////////////////////////////////
/////// [CORS] dependencies ////////
////////////////////////////////////
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::Header;
use rocket::{Request, Response};

//////////////////////////////////////
/////// [rocket] dependencies ////////
//////////////////////////////////////
use rocket::http::Status;
use rocket::launch;
use rocket::response::{content, status};
Expand All @@ -16,6 +26,37 @@ use serde::{Deserialize, Serialize};
// Required [modules].
use wspr_cdk::{services::prelude::*, state::prelude::*};

// [CORS] setup.
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, req: &'r Request<'_>, res: &mut Response<'r>) {
res.set_header(Header::new("Access-Control-Allow-Origin", "*"));
res.set_header(Header::new(
"Access-Control-Allow-Methods",
"POST, PATCH, PUT, DELETE, HEAD, OPTIONS, GET",
));
res.set_header(Header::new("Access-Control-Allow-Headers", "*"));
res.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
res.set_header(Header::new(
"Content-Security-Policy",
"default-src 'self'; connect-src 'self' http://localhost:8000",
));
}
}

// Handle [RESPONSE] to preflight [REQUESTS].
#[rocket::options("/<_route_args..>")]
pub fn options(_route_args: Option<std::path::PathBuf>) {}

/// Get all <wspr> spots.
#[get("/api/spots")]
async fn get_wspr_spots() -> Result<Json<Vec<WsprSpot>>, status::Custom<String>> {
Expand All @@ -38,7 +79,9 @@ async fn get_wspr_spots() -> Result<Json<Vec<WsprSpot>>, status::Custom<String>>
#[launch]
#[rocket::main]
async fn rocket() -> _ {
rocket::build().mount("/", routes![get_wspr_spots])
rocket::build()
.attach(CORS)
.mount("/", routes![options, get_wspr_spots])
}

/*
Expand Down

0 comments on commit c89b4a6

Please sign in to comment.