1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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();
}
|