Skip to content

Commit

Permalink
example: add AddData Middleware example (refs #445) (#728)
Browse files Browse the repository at this point in the history
* example: add AddData Middleware example (refs #445)

* fix name
  • Loading branch information
attila-lin authored Jan 12, 2024
1 parent 78da54e commit ab91445
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
10 changes: 10 additions & 0 deletions examples/poem/add-data/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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
52 changes: 52 additions & 0 deletions examples/poem/add-data/src/main.rs
Original file line number Diff line number Diff line change
@@ -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<HashMap<String, String>>,
}

#[handler]
fn set_state(Path(name): Path<String>, state: Data<&Arc<AppState>>) -> 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<String>, state: Data<&Arc<AppState>>) -> 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
}

0 comments on commit ab91445

Please sign in to comment.