pavex/response/body/
html.rs

1use std::borrow::Cow;
2
3use bytes::Bytes;
4use http_body_util::Full;
5use mime::TEXT_HTML_UTF_8;
6
7use crate::http::HeaderValue;
8
9use super::TypedBody;
10
11/// A [`Response`](crate::Response) body with `Content-Type` set to
12/// `text/html; charset=utf-8`.
13///
14/// # Example
15///
16/// ```rust
17/// use pavex::{Response, response::body::Html};
18/// use pavex::http::header::CONTENT_TYPE;
19///
20/// let html: Html = r#"<body>
21///     <h1>Hey there!</h1>
22/// </body>"#.into();
23/// let response = Response::ok().set_typed_body(html);
24///
25/// assert_eq!(response.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
26/// ```
27pub struct Html(Bytes);
28
29impl From<String> for Html {
30    fn from(s: String) -> Self {
31        Self(s.into())
32    }
33}
34
35impl From<&'static str> for Html {
36    fn from(s: &'static str) -> Self {
37        Self(Bytes::from_static(s.as_bytes()))
38    }
39}
40
41impl From<Cow<'static, str>> for Html {
42    fn from(s: Cow<'static, str>) -> Self {
43        match s {
44            Cow::Borrowed(s) => s.into(),
45            Cow::Owned(s) => s.into(),
46        }
47    }
48}
49
50impl TypedBody for Html {
51    type Body = Full<Bytes>;
52
53    fn content_type(&self) -> HeaderValue {
54        HeaderValue::from_static(TEXT_HTML_UTF_8.as_ref())
55    }
56
57    fn body(self) -> Self::Body {
58        Full::new(self.0)
59    }
60}