fhtmx_actix/
response.rs

1use actix_web::{
2    HttpResponse,
3    http::header::{
4        ContentType, Header, HeaderName, HeaderValue, InvalidHeaderValue, TryIntoHeaderValue,
5    },
6};
7use fhtmx::prelude::Render;
8
9pub trait FhtmxActixRender {
10    /// Renders as a `ContentType::html()`
11    fn render_response(&self) -> HttpResponse;
12}
13
14impl<T: Render> FhtmxActixRender for T {
15    fn render_response(&self) -> HttpResponse {
16        let html_body = self.render();
17        HttpResponse::Ok()
18            .content_type(ContentType::html())
19            .body(html_body)
20    }
21}
22
23/// Is the HX-Request header present
24pub struct HXRequest(bool);
25
26impl HXRequest {
27    /// Checks if the HX-Request header is present from htmx
28    pub fn is_htmx(&self) -> bool {
29        self.0
30    }
31}
32
33impl TryIntoHeaderValue for HXRequest {
34    type Error = InvalidHeaderValue;
35
36    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
37        HeaderValue::from_str(&self.0.to_string())
38    }
39}
40
41impl Header for HXRequest {
42    fn name() -> HeaderName {
43        HeaderName::from_static("HX-Request")
44    }
45
46    fn parse<M: actix_web::HttpMessage>(msg: &M) -> Result<Self, actix_web::error::ParseError> {
47        let x = msg.headers().contains_key("HX-Request");
48        Ok(Self(x))
49    }
50}