Skip to content

Commit

Permalink
Add Html, Css, JavaScript, and Wasm response types (#1921)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidpdrsn committed Apr 17, 2023
1 parent 018d65d commit e97462d
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 1 deletion.
7 changes: 6 additions & 1 deletion axum-extra/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ and this project adheres to [Semantic Versioning].

# Unreleased

- None.
- **added:** Add `Html` response type ([#1921])
- **added:** Add `Css` response type ([#1921])
- **added:** Add `JavaScript` response type ([#1921])
- **added:** Add `Wasm` response type ([#1921])

[#1921]: https://github.com/tokio-rs/axum/pull/1921

# 0.7.3 (11. April, 2023)

Expand Down
79 changes: 79 additions & 0 deletions axum-extra/src/response/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,82 @@ pub use erased_json::ErasedJson;
#[cfg(feature = "json-lines")]
#[doc(no_inline)]
pub use crate::json_lines::JsonLines;

macro_rules! mime_response {
(
$(#[$m:meta])*
$ident:ident,
$mime:ident,
) => {
mime_response! {
$(#[$m])*
$ident,
mime::$mime.as_ref(),
}
};

(
$(#[$m:meta])*
$ident:ident,
$mime:expr,
) => {
$(#[$m])*
#[derive(Clone, Copy, Debug)]
#[must_use]
pub struct $ident<T>(pub T);

impl<T> axum::response::IntoResponse for $ident<T>
where
T: axum::response::IntoResponse,
{
fn into_response(self) -> axum::response::Response {
(
[(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static($mime),
)],
self.0,
)
.into_response()
}
}

impl<T> From<T> for $ident<T> {
fn from(inner: T) -> Self {
Self(inner)
}
}
};
}

mime_response! {
/// A HTML response.
///
/// Will automatically get `Content-Type: text/html; charset=utf-8`.
Html,
TEXT_HTML_UTF_8,
}

mime_response! {
/// A JavaScript response.
///
/// Will automatically get `Content-Type: application/javascript; charset=utf-8`.
JavaScript,
APPLICATION_JAVASCRIPT_UTF_8,
}

mime_response! {
/// A CSS response.
///
/// Will automatically get `Content-Type: text/css; charset=utf-8`.
Css,
TEXT_CSS_UTF_8,
}

mime_response! {
/// A WASM response.
///
/// Will automatically get `Content-Type: application/wasm`.
Wasm,
"application/wasm",
}

0 comments on commit e97462d

Please sign in to comment.