Skip to content

Commit

Permalink
Add struct NoContent as a self-described shortcut (#2978)
Browse files Browse the repository at this point in the history
  • Loading branch information
oxalica authored and jplatte committed Nov 14, 2024
1 parent 236781c commit dcb4af6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
2 changes: 2 additions & 0 deletions axum/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
35 changes: 34 additions & 1 deletion axum/src/response/mod.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -60,6 +60,31 @@ impl<T> From<T> for Html<T> {
}
}

/// 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<String>) -> Result<NoContent, String> {
/// // ...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;
Expand Down Expand Up @@ -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,
)
}
}

0 comments on commit dcb4af6

Please sign in to comment.