use athene::prelude::*; use tracing::info; #[derive(Serialize, Deserialize,Clone)] pub struct User { pub username: String, pub age: u16, } // 127.0.0.1:7878/user/sign_up pub async fn sign_up(mut req: Request) -> impl Responder { let user = req.parse::().await?; Ok::<_, Error>((200, Json(user))) } // 127.0.0.1:7878/user/login pub async fn login(mut req: Request) -> impl Responder { match req.parse::().await { Ok(user) => (201,Json(user)), Err(_) => { let user = req.extensions_mut().get::().unwrap(); let user = user.clone(); (404,Json(user)) } } } pub fn user_router(r: Router) -> Router { r.post("/user/login", login) .post("/user/sign_up", sign_up) } pub async fn log_middleware(mut ctx: Context, next: &dyn Next) -> Result { let req = ctx.state.request_mut()?; let uri_path = req.uri().path(); info!("new request on path: {:?}", uri_path); let user = User {username: "admin2023".to_string(),age: 18}; req.extensions_mut().insert(user); let next_ctx = next.next(ctx).await?; let res = next_ctx.state.response()?; let status = res.status(); info!("new response with status: {:?}", status); let body = res.body(); info!("new response body: {:?}", body); Ok(next_ctx) } #[tokio::main] pub async fn main() -> Result<()> { tracing_subscriber::fmt().compact().init(); let app = athene::new().router(user_router).middleware(|m| { m.apply(log_middleware, vec!["/"], None) }); app.listen("127.0.0.1:7878").await }