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

Implement Handler for T: IntoResponse #2140

Merged
merged 3 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions axum/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **fixed:** Allow unreachable code in `#[debug_handler]` ([#2014])
- **change:** Update tokio-tungstenite to 0.19 ([#2021])
- **change:** axum's MSRV is now 1.63 ([#2021])
- **added:** Implement `Handler` for `T: IntoResponse` ([#2140])

[#2021]: https://github.com/tokio-rs/axum/pull/2021
[#2014]: https://github.com/tokio-rs/axum/pull/2014
Expand All @@ -78,6 +79,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[#2058]: https://github.com/tokio-rs/axum/pull/2058
[#2073]: https://github.com/tokio-rs/axum/pull/2073
[#2096]: https://github.com/tokio-rs/axum/pull/2096
[#2140]: https://github.com/tokio-rs/axum/pull/2140

# 0.6.17 (25. April, 2023)

Expand Down
42 changes: 42 additions & 0 deletions axum/src/handler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,31 @@ pub use self::service::HandlerService;
/// {}
/// ```
#[doc = include_str!("../docs/debugging_handler_type_errors.md")]
///
/// # Handlers that aren't functions
///
/// The `Handler` trait is also implemented for `T: IntoResponse`. That allows easily returning
/// fixed data for routes:
///
/// ```
/// use axum::{
/// Router,
/// routing::{get, post},
/// Json,
/// http::StatusCode,
/// };
/// use serde_json::json;
///
/// let app = Router::new()
/// // respond with a fixed string
/// .route("/", get("Hello, World!"))
/// // or return some mock data
/// .route("/users", post((
/// StatusCode::CREATED,
/// Json(json!({ "id": 1, "username": "alice" })),
/// )));
/// # let _: Router = app;
/// ```
#[cfg_attr(
nightly_error_messages,
rustc_on_unimplemented(
Expand Down Expand Up @@ -224,6 +249,23 @@ macro_rules! impl_handler {

all_the_tuples!(impl_handler);

mod private {
// Marker type for `impl<T: IntoResponse> Handler for T`
#[allow(missing_debug_implementations)]
pub enum IntoResponseHandler {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this needs to have pub visibility? At least on my v0.6.x based branch, things compiled with a private marker type.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It didn't actually work when I tried using it

error: type `handler::IntoResponseHandler` is private
  --> examples/hello-world/src/main.rs:12:40
   |
12 |     let app = Router::new().route("/", get(StatusCode::OK));
   |                                        ^^^ private type

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What, at the usage site?? 😱

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah that confused me as well. Haven't seen that before.

}

impl<T, S> Handler<private::IntoResponseHandler, S> for T
where
T: IntoResponse + Clone + Send + 'static,
{
type Future = std::future::Ready<Response>;

fn call(self, _req: Request, _state: S) -> Self::Future {
std::future::ready(self.into_response())
}
}

/// A [`Service`] created from a [`Handler`] by applying a Tower middleware.
///
/// Created with [`Handler::layer`]. See that method for more details.
Expand Down
11 changes: 11 additions & 0 deletions axum/src/routing/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1021,3 +1021,14 @@ async fn connect_going_to_default_fallback() {
let body = hyper::body::to_bytes(res).await.unwrap();
assert!(body.is_empty());
}

#[crate::test]
async fn impl_handler_for_into_response() {
let app = Router::new().route("/things", post((StatusCode::CREATED, "thing created")));

let client = TestClient::new(app);

let res = client.post("/things").send().await;
assert_eq!(res.status(), StatusCode::CREATED);
assert_eq!(res.text().await, "thing created");
}