-
Notifications
You must be signed in to change notification settings - Fork 327
allow for function middlewares by dropping Debug bound and add example #545
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,101 @@ | ||
| use std::future::Future; | ||
| use std::pin::Pin; | ||
| use std::sync::atomic::{AtomicUsize, Ordering}; | ||
| use std::sync::Arc; | ||
| use tide::{Middleware, Next, Request, Response, Result, StatusCode}; | ||
|
|
||
| #[derive(Debug)] | ||
| struct User { | ||
| name: String, | ||
| } | ||
|
|
||
| #[derive(Default)] | ||
| struct UserDatabase; | ||
| impl UserDatabase { | ||
| async fn find_user(&self) -> Option<User> { | ||
| Some(User { | ||
| name: "nori".into(), | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| // This is an example of a function middleware that uses the | ||
| // application state. Because it depends on a specific request state, | ||
| // it would likely be closely tied to a specific application | ||
| fn user_loader<'a>( | ||
| mut request: Request<UserDatabase>, | ||
| next: Next<'a, UserDatabase>, | ||
| ) -> Pin<Box<dyn Future<Output = Result> + Send + 'a>> { | ||
| Box::pin(async { | ||
| if let Some(user) = request.state().find_user().await { | ||
| tide::log::trace!("user loaded", {user: user.name}); | ||
| request.set_ext(user); | ||
| next.run(request).await | ||
| // this middleware only needs to run before the endpoint, so | ||
| // it just passes through the result of Next | ||
| } else { | ||
| // do not run endpoints, we could not find a user | ||
| Ok(Response::new(StatusCode::Unauthorized)) | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| // | ||
| // | ||
| // this is an example of middleware that keeps its own state and could | ||
| // be provided as a third party crate | ||
| #[derive(Default)] | ||
| struct RequestCounterMiddleware { | ||
| requests_counted: Arc<AtomicUsize>, | ||
| } | ||
|
|
||
| impl RequestCounterMiddleware { | ||
| fn new(start: usize) -> Self { | ||
| Self { | ||
| requests_counted: Arc::new(AtomicUsize::new(start)), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| struct RequestCount(usize); | ||
|
|
||
| impl<State: Send + Sync + 'static> Middleware<State> for RequestCounterMiddleware { | ||
| fn handle<'a>( | ||
| &'a self, | ||
| mut req: Request<State>, | ||
| next: Next<'a, State>, | ||
| ) -> Pin<Box<dyn Future<Output = Result> + Send + 'a>> { | ||
| Box::pin(async move { | ||
| let count = self.requests_counted.fetch_add(1, Ordering::Relaxed); | ||
| tide::log::trace!("request counter", { count: count }); | ||
| req.set_ext(RequestCount(count)); | ||
|
|
||
| let mut response = next.run(req).await?; | ||
|
|
||
| response = response.set_header("request-number", count.to_string()); | ||
| Ok(response) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| #[async_std::main] | ||
| async fn main() -> Result<()> { | ||
| tide::log::start(); | ||
| let mut app = tide::with_state(UserDatabase::default()); | ||
|
|
||
| app.middleware(user_loader); | ||
| app.middleware(RequestCounterMiddleware::new(0)); | ||
|
|
||
| app.at("/").get(|req: Request<_>| async move { | ||
| let count: &RequestCount = req.ext().unwrap(); | ||
| let user: &User = req.ext().unwrap(); | ||
|
|
||
| Ok(format!( | ||
| "Hello {}, this was request number {}!", | ||
| user.name, count.0 | ||
| )) | ||
| }); | ||
|
|
||
| app.listen("127.0.0.1:8080").await?; | ||
| Ok(()) | ||
| } |
This file contains hidden or 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
This file contains hidden or 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.