port to rocket

This commit is contained in:
41666 2022-11-20 23:17:23 -05:00
parent dae504b7af
commit c0bb19e849
4 changed files with 653 additions and 427 deletions

944
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -6,8 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
salvo = { version = "0.37.4", features = ["cors"] }
tokio = { version = "1.22.0", features = ["macros"] }
rocket = { version = "0.5.0-rc.2", features = ["json"] }
serde_json = "1.0.88"
serde = "1.0.147"
redis = { version = "0.22.1", default_features = false, features = [] }

25
services/api/src/cors.rs Normal file
View file

@ -0,0 +1,25 @@
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::Header;
use rocket::{Request, Response};
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, PATCH, OPTIONS",
));
response.set_header(Header::new("Access-Control-Allow-Headers", "*"));
response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
}
}

View file

@ -1,11 +1,13 @@
pub mod cors;
use core::time;
use once_cell::sync::Lazy;
use rocket::{data::Outcome, http::uri::Host, request::FromRequest, Build, Request, Rocket};
use serde::{Deserialize, Serialize};
use std::{ops::Sub, time::SystemTime};
use once_cell::sync::Lazy;
use salvo::cors::Cors;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate serde_json;
@ -39,52 +41,24 @@ pub static REDIS_CLIENT: Lazy<redis::Client> = Lazy::new(|| {
.unwrap()
});
#[handler]
async fn info(req: &mut Request, res: &mut Response) {
let headers: IncomingHeaders = req.parse_headers().unwrap();
let json = json!({
fn hello(host: String) -> serde_json::Value {
json!({
"@": "Saerro Listening Post - PlanetSide 2 Live Population API",
"@GitHub": "https://github.com/genudine/saerro",
"@Disclaimer": "Genudine Dynamics is not responsible for any damages caused by this software. Use at your own risk.",
"@Support": "#api-dev in https://discord.com/servers/planetside-2-community-251073753759481856",
"Worlds": {
"Connery": format!("https://{}/w/1", headers.host),
"Miller": format!("https://{}/w/10", headers.host),
"Cobalt": format!("https://{}/w/13", headers.host),
"Emerald": format!("https://{}/w/17", headers.host),
"Jaeger": format!("https://{}/w/19", headers.host),
"SolTech": format!("https://{}/w/40", headers.host),
"Genudine": format!("https://{}/w/1000", headers.host),
"Ceres": format!("https://{}/w/2000", headers.host),
"Connery": format!("https://{}/w/1", host),
"Miller": format!("https://{}/w/10", host),
"Cobalt": format!("https://{}/w/13", host),
"Emerald": format!("https://{}/w/17", host),
"Jaeger": format!("https://{}/w/19", host),
"SolTech": format!("https://{}/w/40", host),
"Genudine": format!("https://{}/w/1000", host),
"Ceres": format!("https://{}/w/2000", host),
},
"All Worlds": format!("https://{}/m/?ids=1,10,13,17,19,40,1000,2000", headers.host),
});
res.render(serde_json::to_string_pretty(&json).unwrap());
}
#[handler]
async fn get_world(req: &mut Request, res: &mut Response) {
let world_id: String = req.param("worldID").unwrap();
let response = get_world_pop(world_id).await;
res.render(Json(response));
}
#[handler]
async fn get_world_multi(req: &mut Request, res: &mut Response) {
let world_ids_raw = req.query::<String>("ids").unwrap();
let world_ids: Vec<&str> = world_ids_raw.split(",").collect();
let mut response = MultipleWorldPopulation { worlds: Vec::new() };
for world_id in world_ids {
response
.worlds
.push(get_world_pop(world_id.to_string()).await);
}
res.render(Json(response));
"All Worlds": format!("https://{}/m/?ids=1,10,13,17,19,40,1000,2000", host),
})
}
async fn get_world_pop(world_id: String) -> WorldPopulation {
@ -115,22 +89,32 @@ async fn get_world_pop(world_id: String) -> WorldPopulation {
response
}
#[tokio::main]
async fn main() {
let port = ::std::env::var("PORT").unwrap_or("7878".to_string());
let addr = format!("127.0.0.1:{}", port);
#[get("/w/<world_id>")]
async fn world_pop(world_id: String) -> serde_json::Value {
let response = get_world_pop(world_id).await;
let cors_handler = Cors::builder()
.allow_any_origin()
.allow_method("GET")
.build();
println!("Listening on http://localhost:{}", port);
let router = Router::new()
.hoop(cors_handler)
.push(Router::with_path("/").get(info))
.push(Router::with_path("/w/<worldID>").get(get_world))
.push(Router::with_path("/m/").get(get_world_multi));
Server::new(TcpListener::bind(&addr)).serve(router).await;
json!(response)
}
#[get("/m?<ids>")]
async fn multiple_world_pop(ids: String) -> serde_json::Value {
let mut response = MultipleWorldPopulation { worlds: vec![] };
for id in ids.split(",") {
response.worlds.push(get_world_pop(id.to_string()).await);
}
json!(response)
}
#[get("/")]
async fn index() -> serde_json::Value {
hello("saerro.harasse.rs".to_string())
}
#[launch]
fn rocket() -> Rocket<Build> {
rocket::build()
.attach(cors::CORS)
.mount("/", routes![index, world_pop, multiple_world_pop])
}