use axum::{response::IntoResponse, routing::get, Router}; use axum_extra::extract::cookie::{Cookie, CookieJar}; use clap::Parser; use rand::distributions::{Alphanumeric, DistString}; const LOCALHOST: &str = "127.0.0.1"; const SESSION_KEY: &str = "sessionid"; #[derive(Parser, Debug)] #[command(version, about, long_about = None)] struct Args { /// Post used #[arg(short, long, default_value_t = 3000)] port: u16, /// IP used #[arg(short, long, default_value_t = LOCALHOST.to_string())] address: String, } #[cfg(test)] mod http_session { #[tokio::test] async fn my_test() { assert!(true); } } #[tokio::main] async fn main() { let args = Args::parse(); let addr = format!("{}:{}", args.address, args.port); let app = Router::new().route("/", get(handler)); let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); axum::serve(listener, app.into_make_service()) .await .unwrap(); } async fn handler(jar: CookieJar) -> impl IntoResponse { let cookies: CookieJar; let id: String; match jar.get(SESSION_KEY) { Some(session) => { id = session.to_string(); cookies = jar; } None => { id = Alphanumeric.sample_string(&mut rand::thread_rng(), 16); let cookie = Cookie::build((SESSION_KEY, id.clone())).domain("example.com"); cookies = jar.add(cookie); } } (cookies, format!("id is {}", id)) }