|
// Nightly-only language features needed by Rocket |
|
#![feature(proc_macro_hygiene, decl_macro)] |
|
|
|
// Import the rocket macros |
|
#[macro_use] |
|
extern crate rocket; |
|
#[macro_use] |
|
extern crate serde; |
|
#[macro_use] |
|
extern crate lazy_static; |
|
|
|
use rocket_contrib::templates::Template; |
|
use rocket_contrib::serve::StaticFiles; |
|
use serde::{Deserialize, Serialize}; |
|
use std::{ |
|
sync::{Arc, RwLock}, |
|
}; |
|
use uuid::Uuid; |
|
use tera::Context; |
|
use serde_yaml; |
|
|
|
|
|
type Clusters = Arc<RwLock<Vec<Cluster>>>; |
|
|
|
lazy_static! { |
|
pub static ref CLUSTERS: Clusters = Arc::new(RwLock::new(Vec::new())); |
|
} |
|
|
|
fn add_cluster(c: Cluster) { |
|
let clusters = Arc::clone(&CLUSTERS); |
|
let mut lock = clusters.write().unwrap(); |
|
lock.push(c); |
|
} |
|
|
|
fn remove_cluster(id: Uuid) { |
|
let clusters = Arc::clone(&CLUSTERS); |
|
let mut lock = clusters.write().unwrap(); |
|
// find the index |
|
let mut idx = lock.len(); |
|
for (i, cluster) in lock.iter().enumerate() { |
|
if cluster.id == id { |
|
idx = i; |
|
} |
|
} |
|
// remove that element if found |
|
if idx < lock.len() { |
|
lock.remove(idx); |
|
} |
|
} |
|
|
|
#[derive(Serialize, Deserialize, Debug)] |
|
struct Person { |
|
name: String, |
|
age: u8, |
|
phones: Vec<String>, |
|
} |
|
|
|
#[derive(Debug, Serialize, Deserialize)] |
|
pub struct Cluster { |
|
name: String, |
|
id: Uuid, |
|
} |
|
|
|
impl Cluster { |
|
fn new(name: &str) -> Self { |
|
Self { |
|
id: Uuid::new_v4(), |
|
name: String::from(name), |
|
} |
|
} |
|
} |
|
|
|
/// Create route /index that returns html page |
|
#[get("/")] |
|
fn index() -> Template { |
|
|
|
let clustername = String::from("cluster1"); |
|
add_cluster(Cluster::new(&clustername)); |
|
// just to test that context can have many objects |
|
let p = Person { |
|
name: "Maxim".to_owned(), |
|
age: 18, |
|
phones: vec!["1234".to_owned()], |
|
}; |
|
|
|
let clusters = Arc::clone(&CLUSTERS); |
|
let lock = clusters.read().unwrap(); |
|
let mut ctx = Context::new(); |
|
ctx.insert("clusters", &*lock); |
|
ctx.insert("clustersLen", &(*lock).len()); |
|
ctx.insert("person", &p); |
|
Template::render("index", ctx.into_json()) |
|
} |
|
|
|
|
|
fn main() { |
|
rocket::ignite() |
|
.mount("/", routes![index]) |
|
.mount("/vendor", StaticFiles::from(concat!(env!("CARGO_MANIFEST_DIR"), "/static/vendor"))) |
|
.attach(Template::fairing()) |
|
.launch(); |
|
} |