From ab91445b0cd54b5b5c72091d1837ae2932dd981a Mon Sep 17 00:00:00 2001 From: Yiyu Lin Date: Fri, 12 Jan 2024 17:23:10 +0800 Subject: [PATCH] example: add AddData Middleware example (refs #445) (#728) * example: add AddData Middleware example (refs #445) * fix name --- examples/poem/add-data/Cargo.toml | 10 ++++++ examples/poem/add-data/src/main.rs | 52 ++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 examples/poem/add-data/Cargo.toml create mode 100644 examples/poem/add-data/src/main.rs diff --git a/examples/poem/add-data/Cargo.toml b/examples/poem/add-data/Cargo.toml new file mode 100644 index 0000000000..4944c3b3e1 --- /dev/null +++ b/examples/poem/add-data/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "example-add-data" +version.workspace = true +edition.workspace = true +publish.workspace = true + +[dependencies] +poem.workspace = true +tokio = { workspace = true, features = ["rt-multi-thread", "macros"] } +tracing-subscriber.workspace = true \ No newline at end of file diff --git a/examples/poem/add-data/src/main.rs b/examples/poem/add-data/src/main.rs new file mode 100644 index 0000000000..60b4da8dda --- /dev/null +++ b/examples/poem/add-data/src/main.rs @@ -0,0 +1,52 @@ +use std::{ + collections::HashMap, + sync::{Arc, Mutex}, +}; + +use poem::{ + get, handler, + listener::TcpListener, + middleware::AddData, + web::{Data, Path}, + EndpointExt, Route, Server, +}; + +struct AppState { + clients: Mutex>, +} + +#[handler] +fn set_state(Path(name): Path, state: Data<&Arc>) -> String { + let mut store = state.clients.lock().unwrap(); + store.insert(name.to_string(), "some state object".to_string()); + "store updated".to_string() +} + +#[handler] +fn get_state(Path(name): Path, state: Data<&Arc>) -> String { + let store = state.clients.lock().unwrap(); + let message = store.get(&name).unwrap(); + message.to_string() +} + +#[tokio::main] +async fn main() -> Result<(), std::io::Error> { + if std::env::var_os("RUST_LOG").is_none() { + std::env::set_var("RUST_LOG", "poem=debug"); + } + tracing_subscriber::fmt::init(); + + let state = Arc::new(AppState { + clients: Mutex::new(HashMap::new()), + }); + + let app = Route::new() + .at("/hello/:name", get(set_state)) + .at("/:name", get(get_state)) + .with(AddData::new(state)); + + Server::new(TcpListener::bind("0.0.0.0:3000")) + .name("add-data") + .run(app) + .await +}