Skip to content

Commit 7baf982

Browse files
committed
add Cors, dotenv and clippy
1 parent e08a1cc commit 7baf982

File tree

7 files changed

+64
-8
lines changed

7 files changed

+64
-8
lines changed

.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
/target
2-
.direnv
2+
.direnv
3+
.env

Cargo.lock

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ nanoid = "0.4.0"
88
url = "2.2.2"
99
bb8 = "0.7.0"
1010
bb8-redis = "0.9.0"
11+
dotenv = "0.15.0"
1112

1213
[dependencies.redis]
1314
version = "0.20.2"

Rocket.toml

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[debug]
2+
port = 8080

flake.nix

+3-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
in rec {
1212
# `nix build`
1313
packages.my-project = naersk-lib.buildPackage {
14-
pname = "my-project";
14+
pname = "ulink";
1515
root = ./.;
1616
};
1717
defaultPackage = packages.my-project;
@@ -24,7 +24,7 @@
2424

2525
# `nix develop`
2626
devShell = pkgs.mkShell {
27-
nativeBuildInputs = with pkgs; [ rustc cargo rust-analyzer ];
27+
nativeBuildInputs = with pkgs; [ rustc cargo clippy rust-analyzer docker-compose ];
2828
};
2929
});
30-
}
30+
}

src/db.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::ops::{Deref, DerefMut};
1+
use std::{ops::{Deref, DerefMut}};
22

33
use bb8_redis::RedisConnectionManager;
44
use rocket::{

src/main.rs

+48-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
extern crate dotenv;
2+
13
mod consts;
24
mod db;
35
mod models;
@@ -6,10 +8,15 @@ use bb8_redis::redis::AsyncCommands;
68
use db::RedisConnection;
79
use models::{NewShorterURL, ShorterURL};
810
use nanoid::nanoid;
9-
use rocket::response::status::Created;
11+
use rocket::{http::{ContentType, Method}, response::status::Created};
1012
use rocket::response::Redirect;
1113
use rocket::serde::json::Json;
12-
use rocket::{get, launch, post, routes, Responder};
14+
use rocket::{get, launch, post, options, routes, Request, Response, Responder};
15+
use rocket::http::Header;
16+
use rocket::fairing::{Fairing, Info, Kind};
17+
use dotenv::dotenv;
18+
use std::env;
19+
1320

1421
const REDIS_KEY_PREFIX: &str = "microshort::ids";
1522

@@ -18,6 +25,9 @@ async fn index() -> &'static str {
1825
"Hello, world!"
1926
}
2027

28+
#[options("/")]
29+
async fn cors() {}
30+
2131
#[post("/", format = "json", data = "<data>")]
2232
async fn shorten(
2333
data: Json<NewShorterURL>,
@@ -27,6 +37,8 @@ async fn shorten(
2737
let id = nanoid!(4, &consts::ALPHANUMERIC);
2838
let key = format!("{}::{}", REDIS_KEY_PREFIX, id);
2939
let result = conn.set_nx(&key, &data.url).await.expect("RedisSetNXError");
40+
41+
conn.expire::<&str, usize>(&key, data.duration).await.expect("RedisExpireError");
3042

3143
if result {
3244
break id;
@@ -58,9 +70,42 @@ async fn access(id: &str, mut conn: RedisConnection<'_>) -> AccessResponse {
5870
}
5971
}
6072

73+
struct Cors;
74+
75+
#[rocket::async_trait]
76+
impl Fairing for Cors {
77+
fn info(&self) -> Info {
78+
Info {
79+
name: "My Custom Fairing",
80+
kind: Kind::Response
81+
}
82+
}
83+
84+
async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
85+
let origin = match env::var("ORIGIN_ADDRESS") {
86+
Ok(val) => val,
87+
Err(e) => panic!("{}", e),
88+
};
89+
90+
if req.method() == Method::Options || res.content_type() == Some(ContentType::JSON) {
91+
res.set_header(Header::new("Access-Control-Allow-Origin", origin));
92+
res.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, OPTIONS"));
93+
res.set_header(Header::new("Access-Control-Allow-Headers", "Content-Type"));
94+
res.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
95+
}
96+
97+
if req.method() == Method::Options {
98+
res.set_header(ContentType::Plain);
99+
}
100+
}
101+
}
102+
61103
#[launch]
62104
async fn rocket() -> _ {
105+
dotenv().ok();
106+
63107
rocket::build()
108+
.attach(Cors)
64109
.manage(db::pool().await)
65-
.mount("/", routes![index, access, shorten])
110+
.mount("/", routes![index, access, shorten, cors])
66111
}

0 commit comments

Comments
 (0)