From edaa8bf6d400b38a937c38d8098e169c940fd45f Mon Sep 17 00:00:00 2001 From: John Parton Date: Mon, 11 Sep 2023 09:51:20 -0500 Subject: [PATCH] Add example with middleware with state using async_std Mutex. --- src/middleware/mod.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/middleware/mod.rs b/src/middleware/mod.rs index 88cedff1..0f46d30d 100644 --- a/src/middleware/mod.rs +++ b/src/middleware/mod.rs @@ -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, +//! } +//! +//! 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 { +//! { +//! let mut guard = self.seen_count.try_lock().unwrap(); +//! *guard += 1; +//! +//! println!("Seen count: {}", *guard); +//! } +//! +//! next.run(req, client).await +//! } +//! } +//! ``` use std::sync::Arc;