summaryrefslogtreecommitdiff
path: root/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.rs')
-rw-r--r--src/main.rs72
1 files changed, 72 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs
new file mode 100644
index 0000000..f0775b5
--- /dev/null
+++ b/src/main.rs
@@ -0,0 +1,72 @@
+use axum::{
+ extract::{Query, State},
+ response::{Html, IntoResponse},
+ routing::{get, post},
+ Json, Router,
+};
+use serde::Serialize;
+use std::fs;
+use std::net::SocketAddr;
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex},
+};
+use uuid::Uuid;
+
+#[derive(Default)]
+struct AppState {
+ sessions: Mutex<HashMap<String, String>>,
+}
+
+#[derive(Serialize)]
+struct EchoResponse {
+ name: String,
+ session_id: String,
+}
+
+async fn echo(
+ State(state): State<Arc<AppState>>,
+ Query(params): Query<HashMap<String, String>>,
+) -> Json<EchoResponse> {
+ let name = params.get("name").cloned().unwrap_or_default();
+ let session_id = Uuid::new_v4().to_string();
+
+ state
+ .sessions
+ .lock()
+ .unwrap()
+ .insert(session_id.clone(), name.clone());
+
+ Json(EchoResponse { name, session_id })
+}
+
+#[tokio::main]
+async fn main() {
+ let state = Arc::new(AppState::default());
+
+ let port: u16 = std::env::var("PORT")
+ .unwrap_or_else(|_| "3000".into())
+ .parse()
+ .expect("PORT must be a number");
+
+ let addr = SocketAddr::from(([127, 0, 0, 1], port));
+
+ let app = Router::new()
+ .route(
+ "/",
+ get(|| async {
+ // Serve the default index.html
+ match fs::read_to_string("static/index.html") {
+ Ok(html) => Html(html).into_response(),
+ Err(_) => "Index not found".into_response(),
+ }
+ }),
+ )
+ .route("/api/echo", post(echo))
+ .with_state(state);
+
+ axum::Server::bind(&addr)
+ .serve(app.into_make_service())
+ .await
+ .unwrap();
+}