Skip to content

Commit 80c4ead

Browse files
authored
Improve documentation about sharing state with handlers (#3333)
1 parent 53631b2 commit 80c4ead

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

axum/src/lib.rs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -148,10 +148,12 @@
148148
//! pool of database connections or clients to other services may need to
149149
//! be shared.
150150
//!
151-
//! The three most common ways of doing that are:
151+
//! The four most common ways of doing that are:
152+
//!
152153
//! - Using the [`State`] extractor
153154
//! - Using request extensions
154155
//! - Using closure captures
156+
//! - Using task-local variables
155157
//!
156158
//! ## Using the [`State`] extractor
157159
//!
@@ -182,13 +184,13 @@
182184
//! ```
183185
//!
184186
//! You should prefer using [`State`] if possible since it's more type safe. The downside is that
185-
//! it's less dynamic than request extensions.
187+
//! it's less dynamic than task-local variables and request extensions.
186188
//!
187189
//! See [`State`] for more details about accessing state.
188190
//!
189191
//! ## Using request extensions
190192
//!
191-
//! Another way to extract state in handlers is using [`Extension`](crate::extract::Extension) as
193+
//! Another way to share state with handlers is using [`Extension`](crate::extract::Extension) as
192194
//! layer and extractor:
193195
//!
194196
//! ```rust,no_run
@@ -273,12 +275,11 @@
273275
//! # let _: Router = app;
274276
//! ```
275277
//!
276-
//! The downside to this approach is that it's a little more verbose than using
277-
//! [`State`] or extensions.
278+
//! The downside to this approach is that it's a the most verbose approach.
278279
//!
279-
//! ## Using [tokio's `task_local` macro](https://docs.rs/tokio/1/tokio/macro.task_local.html):
280+
//! ## Using task-local variables
280281
//!
281-
//! This allows to share state with `IntoResponse` implementations.
282+
//! This also allows to share state with `IntoResponse` implementations:
282283
//!
283284
//! ```rust,no_run
284285
//! use axum::{
@@ -337,6 +338,12 @@
337338
//! .route_layer(middleware::from_fn(auth));
338339
//! ```
339340
//!
341+
//! The main downside to this approach is that it only works when the async executor being used
342+
//! has the concept of task-local variables. The example above uses
343+
//! [tokio's `task_local` macro](https://docs.rs/tokio/1/tokio/macro.task_local.html).
344+
//! smol does not yet offer equivalent functionality at the time of writing (see
345+
//! [this GitHub issue](https://github.com/smol-rs/async-executor/issues/139)).
346+
//!
340347
//! # Building integrations for axum
341348
//!
342349
//! Libraries authors that want to provide [`FromRequest`], [`FromRequestParts`], or

0 commit comments

Comments
 (0)