Skip to main content

hemplate_axum/
lib.rs

1//! axum integration for hemplate templates.
2//!
3//! Wrap any [`Hemplate`] type in [`HtmlTemplate`] (or [`StatusTemplate`]) to
4//! return it from an axum handler:
5//!
6//! ```ignore
7//! async fn home() -> HtmlTemplate<HomeView> {
8//!     HomeView { title: "Welcome".into() }.into()
9//! }
10//! ```
11//!
12//! No blanket `impl<T: Hemplate> IntoResponse for T` exists — Rust's coherence
13//! rules forbid it (foreign trait + foreign type + overlap with axum's existing
14//! blanket impls). The wrapper is the canonical workaround, matching axum's own
15//! `Json` / `Html` / `Form` newtypes.
16
17#![doc = include_str!("../README.md")]
18
19use axum_core::response::{IntoResponse, Response};
20use hemplate_runtime::Hemplate;
21use http::{header, StatusCode};
22
23/// Wrapper that converts a [`Hemplate`] type into a 200 OK axum [`Response`]
24/// with `Content-Type: text/html; charset=utf-8`.
25///
26/// Render errors map to 500 Internal Server Error with a plain-text body —
27/// applications wanting different error policy should wrap the template
28/// themselves rather than reaching for configuration on this type.
29///
30/// ```ignore
31/// async fn home() -> HtmlTemplate<HomePage> {
32///     HomePage { title: "Welcome".into() }.into_html()
33/// }
34/// ```
35pub struct HtmlTemplate<T: Hemplate>(pub T);
36
37impl<T: Hemplate> From<T> for HtmlTemplate<T> {
38    fn from(view: T) -> Self {
39        Self(view)
40    }
41}
42
43impl<T: Hemplate> IntoResponse for HtmlTemplate<T> {
44    fn into_response(self) -> Response {
45        match self.0.render() {
46            Ok(html) => {
47                ([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response()
48            }
49            Err(err) => (
50                StatusCode::INTERNAL_SERVER_ERROR,
51                format!("Template render error: {err}"),
52            )
53                .into_response(),
54        }
55    }
56}
57
58/// Wrapper for pairing a [`Hemplate`] type with an HTTP status code.
59///
60/// ```ignore
61/// async fn not_found() -> StatusTemplate<NotFoundPage> {
62///     NotFoundPage { path: "/oops".into() }.with_status(StatusCode::NOT_FOUND)
63/// }
64/// ```
65pub struct StatusTemplate<T: Hemplate>(pub StatusCode, pub T);
66
67impl<T: Hemplate> IntoResponse for StatusTemplate<T> {
68    fn into_response(self) -> Response {
69        match self.1.render() {
70            Ok(html) => (
71                self.0,
72                [(header::CONTENT_TYPE, "text/html; charset=utf-8")],
73                html,
74            )
75                .into_response(),
76            Err(err) => (
77                StatusCode::INTERNAL_SERVER_ERROR,
78                format!("Template render error: {err}"),
79            )
80                .into_response(),
81        }
82    }
83}
84
85/// Ergonomic extension methods for any [`Hemplate`] type — chainable wrapper
86/// construction without naming the wrapper type at the call site.
87///
88/// ```ignore
89/// async fn home() -> impl IntoResponse {
90///     HomePage { title: "Welcome".into() }.into_html()
91/// }
92///
93/// async fn not_found() -> impl IntoResponse {
94///     NotFoundPage { path: "/oops".into() }.with_status(StatusCode::NOT_FOUND)
95/// }
96/// ```
97pub trait HemplateExt: Hemplate + Sized {
98    /// Wrap this template as a 200 OK HTML response.
99    fn into_html(self) -> HtmlTemplate<Self> {
100        HtmlTemplate(self)
101    }
102
103    /// Wrap this template as an HTML response with an explicit status code.
104    fn with_status(self, status: StatusCode) -> StatusTemplate<Self> {
105        StatusTemplate(status, self)
106    }
107}
108
109impl<T: Hemplate> HemplateExt for T {}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use hemplate_runtime::RenderError;
115    use http_body_util::BodyExt;
116
117    type TestResult = Result<(), Box<dyn std::error::Error>>;
118
119    struct TestView;
120
121    impl Hemplate for TestView {
122        fn render_into(&self, buf: &mut dyn core::fmt::Write) -> Result<(), RenderError> {
123            buf.write_str("<h1>Hello</h1>")?;
124            Ok(())
125        }
126    }
127
128    fn content_type(resp: &Response) -> Option<&str> {
129        resp.headers()
130            .get(header::CONTENT_TYPE)
131            .and_then(|value| value.to_str().ok())
132    }
133
134    #[tokio::test]
135    async fn html_template_returns_200_with_html_content_type() -> TestResult {
136        let resp = HtmlTemplate(TestView).into_response();
137        assert_eq!(resp.status(), StatusCode::OK);
138        assert_eq!(content_type(&resp), Some("text/html; charset=utf-8"));
139        let body = resp.into_body().collect().await?.to_bytes();
140        assert_eq!(body, "<h1>Hello</h1>");
141        Ok(())
142    }
143
144    #[tokio::test]
145    async fn status_template_returns_custom_status() -> TestResult {
146        let resp = StatusTemplate(StatusCode::NOT_FOUND, TestView).into_response();
147        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
148        assert_eq!(content_type(&resp), Some("text/html; charset=utf-8"));
149        let body = resp.into_body().collect().await?.to_bytes();
150        assert_eq!(body, "<h1>Hello</h1>");
151        Ok(())
152    }
153
154    // --- S89: Render error → 500 INTERNAL_SERVER_ERROR ---
155
156    struct FailView;
157
158    impl Hemplate for FailView {
159        fn render_into(&self, _buf: &mut dyn core::fmt::Write) -> Result<(), RenderError> {
160            Err(RenderError::Fmt(std::fmt::Error))
161        }
162    }
163
164    #[tokio::test]
165    async fn html_template_render_error_returns_500() -> TestResult {
166        let resp = HtmlTemplate(FailView).into_response();
167        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
168        let body = resp.into_body().collect().await?.to_bytes();
169        let text = String::from_utf8_lossy(&body);
170        assert!(
171            text.contains("Template render error"),
172            "error body should contain 'Template render error': {}",
173            text
174        );
175        Ok(())
176    }
177
178    #[tokio::test]
179    async fn status_template_render_error_returns_500() -> TestResult {
180        let resp = StatusTemplate(StatusCode::NOT_FOUND, FailView).into_response();
181        // Even though we asked for 404, render failure → 500
182        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
183        let body = resp.into_body().collect().await?.to_bytes();
184        let text = String::from_utf8_lossy(&body);
185        assert!(
186            text.contains("Template render error"),
187            "error body should contain 'Template render error': {}",
188            text
189        );
190        Ok(())
191    }
192
193    // --- Ergonomics: From + HemplateExt ---
194
195    #[tokio::test]
196    async fn from_view_constructs_html_template() -> TestResult {
197        let wrapped: HtmlTemplate<TestView> = TestView.into();
198        let resp = wrapped.into_response();
199        assert_eq!(resp.status(), StatusCode::OK);
200        let body = resp.into_body().collect().await?.to_bytes();
201        assert_eq!(body, "<h1>Hello</h1>");
202        Ok(())
203    }
204
205    #[tokio::test]
206    async fn ext_into_html_wraps_with_200_and_html_content_type() {
207        let resp = TestView.into_html().into_response();
208        assert_eq!(resp.status(), StatusCode::OK);
209        assert_eq!(content_type(&resp), Some("text/html; charset=utf-8"));
210    }
211
212    #[test]
213    fn adapter_leaves_application_http_policy_outside_its_api() {
214        let source = include_str!("lib.rs").split("#[cfg(test)]").next().unwrap();
215        for forbidden in [
216            "axum::Router",
217            "axum::middleware",
218            "CACHE_CONTROL",
219            "ETAG",
220            "HeaderMap",
221            "tower::",
222        ] {
223            assert!(
224                !source.contains(forbidden),
225                "adapter owns forbidden policy: {forbidden}"
226            );
227        }
228    }
229
230    #[tokio::test]
231    async fn ext_with_status_pairs_view_with_given_status() -> TestResult {
232        let resp = TestView
233            .with_status(StatusCode::IM_A_TEAPOT)
234            .into_response();
235        assert_eq!(resp.status(), StatusCode::IM_A_TEAPOT);
236        let body = resp.into_body().collect().await?.to_bytes();
237        assert_eq!(body, "<h1>Hello</h1>");
238        Ok(())
239    }
240}