use warp::{ Filter, Rejection, Reply, body }; use std::{ collections::HashMap, sync::Arc }; use env_logger; use tokio::sync::Mutex; use uuid::Uuid; use tokio::join; use u_lib::{ MASTER_PORT, contracts::*, client::* }; fn get_content() -> impl Filter,), Error = Rejection> + Clone { body::content_length_limit(1024*64).and(body::json::>()) } async fn add_client(msg: Message<'_, ClientInfo>, db: SharedStorage) -> Result { let new_cli = msg.item; let mut clients = db.lock().await; if clients.contains_key(&new_cli.id) { Ok(warp::reply::json( &RawMsg("Already exist".to_string()).into_message() )) } else { clients.insert( new_cli.id.clone(), UClient::new(new_cli.into_owned()) ); Ok(warp::reply::json( &RawMsg("Added".to_string()).into_message() )) } } async fn listing(db: SharedStorage) -> Result { let clients = db.lock().await; let mut result: Vec = Vec::with_capacity(clients.len()); for cli in clients.values() { result.push(cli.client_info.clone()); } Ok(warp::reply::json( &Message::new_owned(result) )) } #[tokio::main] async fn main() { env_logger::init(); let base_db: SharedStorage = Arc::new( Mutex::new(HashMap::::new()) ); let db = warp::any().map(move || Arc::clone(&base_db)); let new_client = warp::post() .and(warp::path("new")) .and(get_content()) .and(db.clone()) .and_then(add_client); let ls = warp::get() .and(warp::path("ls")) .and(db.clone()) .and_then(listing); let routes = new_client .or(ls) .with(warp::log("warp")); warp::serve(routes) .run(([0,0,0,0], MASTER_PORT)).await; }