Commit
This commit is contained in:
68
src/main.rs
Normal file
68
src/main.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use axum::{routing::post, Json, Router};
|
||||
use once_cell::sync::Lazy;
|
||||
use rand::{thread_rng, Rng};
|
||||
use serde::Deserialize;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// build our application with some routes
|
||||
let app = Router::new().route("/secret-santa-api", post(input));
|
||||
|
||||
// run it with hyper
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3067));
|
||||
axum::Server::bind(&addr)
|
||||
.serve(app.into_make_service())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
static STATE: Lazy<Mutex<State>> = Lazy::new(Mutex::default);
|
||||
|
||||
struct State {
|
||||
rem_a: Vec<String>,
|
||||
rem_b: Vec<String>,
|
||||
}
|
||||
|
||||
fn everyone() -> Vec<String> {
|
||||
vec!["Alice".into(), "Bob".into(), "Carol".into(), "Dave".into()]
|
||||
}
|
||||
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
rem_a: everyone(),
|
||||
rem_b: everyone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct Input {
|
||||
person: String,
|
||||
}
|
||||
|
||||
async fn input(Json(input): Json<Input>) -> String {
|
||||
let mut state = STATE.lock().await;
|
||||
|
||||
if state.rem_a.is_empty() {
|
||||
return "ERROR (everybody drew already)".into();
|
||||
}
|
||||
|
||||
match state.rem_a.iter().position(|p| input.person == *p) {
|
||||
Some(pos) => {
|
||||
state.rem_a.remove(pos);
|
||||
}
|
||||
None => return "ERROR (you drew already)".into(),
|
||||
}
|
||||
|
||||
loop {
|
||||
let num = thread_rng().gen_range(0..state.rem_b.len());
|
||||
if state.rem_b[num] != input.person {
|
||||
return state.rem_b.remove(num);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user