From dcb4af68dee5fcd529e569a8da524dbbe35b1825 Mon Sep 17 00:00:00 2001 From: oxalica Date: Fri, 11 Oct 2024 11:54:11 -0400 Subject: [PATCH] Add `struct NoContent` as a self-described shortcut (#2978) --- axum/CHANGELOG.md | 2 ++ axum/src/response/mod.rs | 35 ++++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/axum/CHANGELOG.md b/axum/CHANGELOG.md index ed355e82..5410ddca 100644 --- a/axum/CHANGELOG.md +++ b/axum/CHANGELOG.md @@ -9,8 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **added:** Add `MethodFilter::CONNECT`, `routing::connect[_service]` and `MethodRouter::connect[_service]` ([#2961]) +- **added:** Add `NoContent` as a self-described shortcut for `StatusCode::NO_CONTENT` ([#2978]) [#2961]: https://github.com/tokio-rs/axum/pull/2961 +[#2978]: https://github.com/tokio-rs/axum/pull/2978 # 0.7.7 diff --git a/axum/src/response/mod.rs b/axum/src/response/mod.rs index 6cfd9b07..4d9664ca 100644 --- a/axum/src/response/mod.rs +++ b/axum/src/response/mod.rs @@ -1,7 +1,7 @@ #![doc = include_str!("../docs/response.md")] use axum_core::body::Body; -use http::{header, HeaderValue}; +use http::{header, HeaderValue, StatusCode}; mod redirect; @@ -60,6 +60,31 @@ impl From for Html { } } +/// An empty response with 204 No Content status. +/// +/// Due to historical and implementation reasons, the `IntoResponse` implementation of `()` +/// (unit type) returns an empty response with 200 [`StatusCode::OK`] status. +/// If you specifically want a 204 [`StatusCode::NO_CONTENT`] status, you can use either `StatusCode` type +/// directly, or this shortcut struct for self-documentation. +/// +/// ``` +/// use axum::{extract::Path, response::NoContent}; +/// +/// async fn delete_user(Path(user): Path) -> Result { +/// // ...access database... +/// # drop(user); +/// Ok(NoContent) +/// } +/// ``` +#[derive(Debug, Clone, Copy)] +pub struct NoContent; + +impl IntoResponse for NoContent { + fn into_response(self) -> Response { + StatusCode::NO_CONTENT.into_response() + } +} + #[cfg(test)] mod tests { use crate::extract::Extension; @@ -224,4 +249,12 @@ mod tests { .route("/", get(header_array_extension_body)) .route("/", get(header_array_extension_mixed_body)); } + + #[test] + fn no_content() { + assert_eq!( + super::NoContent.into_response().status(), + StatusCode::NO_CONTENT, + ) + } }