-
-
Notifications
You must be signed in to change notification settings - Fork 299
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
* example: add AddData Middleware example (refs #445) * fix name
- Loading branch information
1 parent
78da54e
commit ab91445
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |