Backport changes from main to v0.6.x (#2141)

Co-authored-by: David Pedersen <[email protected]>
This commit is contained in:
Jonas Platte
2023-08-03 10:17:27 +02:00
committed by GitHub
co-authored by David Pedersen
parent a25ed293d7
commit 68333b2fcf
5 changed files with 74 additions and 5 deletions
+3
View File
@@ -10,6 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **added:** `WebSocketUpgrade::write_buffer_size` and `WebSocketUpgrade::max_write_buffer_size`
- **changed:** Deprecate `WebSocketUpgrade::max_send_queue`
- **change:** Update tokio-tungstenite to 0.20
- **added:** Implement `Handler` for `T: IntoResponse` ([#2140])
[#2140]: https://github.com/tokio-rs/axum/pull/2140
# 0.6.19 (17. July, 2023)
+43
View File
@@ -103,6 +103,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(
@@ -231,6 +256,24 @@ 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 {}
}
impl<T, S, B> Handler<private::IntoResponseHandler, S, B> for T
where
T: IntoResponse + Clone + Send + 'static,
B: Send + 'static,
{
type Future = std::future::Ready<Response>;
fn call(self, _req: Request<B>, _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.
+11
View File
@@ -1026,3 +1026,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");
}