Skip to content
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

Add example with middleware with state using async_std Mutex. #360

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/middleware/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,45 @@
//! # Ok(())
//! # }
//! ```
//! When introducing state, some care must be taken to avoid blocking the entire thread.
//!
//! ```no_run
//! use async_std;
//! use surf;
//!
//! // Count how many requests have been made
//! struct RequestCounter {
//! // You must use the async_std Mutex to avoid blocking the entire thread
//! seen_count: async_std::sync::Mutex<usize>,
//! }
//!
//! impl Default for RequestCounter {
//! fn default() -> Self {
//! Self {
//! seen_count: async_std::sync::Mutex::new(0),
//! }
//! }
//! }
//!
//! #[surf::utils::async_trait]
//! impl surf::middleware::Middleware for RequestCounter {
//! async fn handle(
//! &self,
//! req: surf::Request,
//! client: surf::Client,
//! next: surf::middleware::Next<'_>,
//! ) -> std::result::Result<surf::Response, http_types::Error> {
//! {
//! let mut guard = self.seen_count.try_lock().unwrap();
//! *guard += 1;
//!
//! println!("Seen count: {}", *guard);
//! }
//!
//! next.run(req, client).await
//! }
//! }
//! ```

use std::sync::Arc;

Expand Down