From e97462d45251c21ffd1ba4fb5db30f3cf6f6cb6c Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Mon, 17 Apr 2023 13:20:17 +0200 Subject: [PATCH] Add `Html`, `Css`, `JavaScript`, and `Wasm` response types (#1921) --- axum-extra/CHANGELOG.md | 7 ++- axum-extra/src/response/mod.rs | 79 ++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/axum-extra/CHANGELOG.md b/axum-extra/CHANGELOG.md index aaf8bc5b64..59944f0e54 100644 --- a/axum-extra/CHANGELOG.md +++ b/axum-extra/CHANGELOG.md @@ -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) diff --git a/axum-extra/src/response/mod.rs b/axum-extra/src/response/mod.rs index 7926b8c815..8bf9c43cda 100644 --- a/axum-extra/src/response/mod.rs +++ b/axum-extra/src/response/mod.rs @@ -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(pub T); + + impl axum::response::IntoResponse for $ident + 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 From for $ident { + 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", +}