catalyzer/response/
builtins.rs1use super::*;
2
3macro_rules! content_types {
4 ($(
5 $(#[$attr:meta])*
6 type $name:ident($content_loader:ident -> $content_type:literal) {
7 $(#[$alloc_attr:meta])*
8 fn new_static($static:ty);
9 $(#[$static_fn_attr:meta])*
10 fn new_alloc($alloc:ty);
11 $(#[$from_file_attr:meta])*
12 fn from_file();
13 }
14 )+) => ($(
15 $(#[$attr])*
16 #[repr(transparent)]
17 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
18 pub struct $name($content_loader);
19
20 impl $name {
21 $(#[$alloc_attr])*
22 #[inline]
23 pub const fn new_static(s: $static) -> Self {
24 Self($content_loader::new_static(s))
25 }
26 $(#[$static_fn_attr])*
27 #[inline]
28 pub fn new_alloc(s: $alloc) -> Self {
29 Self($content_loader::new_alloc(s))
30 }
31 $(#[$from_file_attr])*
32 #[inline]
33 pub async fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
34 $content_loader::from_file(path).await.map(Self)
35 }
36 }
37
38 impl From<$alloc> for $name {
39 #[inline]
40 fn from(this: $alloc) -> Self {
41 Self::new_alloc(this)
42 }
43 }
44
45 impl From<$static> for $name {
46 #[inline]
47 fn from(this: $static) -> Self {
48 Self::new_static(this)
49 }
50 }
51
52 impl fmt::Display for $name {
53 #[inline]
54 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55 self.0.fmt(f)
56 }
57 }
58
59 impl From<$name> for Body {
60 #[inline]
61 fn from(this: $name) -> Self {
62 Body::from(this.0)
63 }
64 }
65
66 impl ::axum::response::IntoResponse for $name {
67 fn into_response(self) -> RawResponse {
68 RawResponse::builder()
69 .header("Content-Type", $content_type)
70 .body(self.into())
71 .unwrap_or_default()
72 }
73 }
74 )+);
75}
76
77content_types! {
78 type Html(StringContentLoader -> "text/html") {
80 fn new_static(&'static str);
82 fn new_alloc(String);
84 fn from_file();
86 }
87 type Css(StringContentLoader -> "text/css") {
89 fn new_static(&'static str);
91 fn new_alloc(String);
93 fn from_file();
95 }
96 type Js(StringContentLoader -> "application/javascript") {
98 fn new_static(&'static str);
100 fn new_alloc(String);
102 fn from_file();
104 }
105 type Json(StringContentLoader -> "application/json") {
107 fn new_static(&'static str);
109 fn new_alloc(String);
111 fn from_file();
113 }
114 type Xml(StringContentLoader -> "application/xml") {
116 fn new_static(&'static str);
118 fn new_alloc(String);
120 fn from_file();
122 }
123 type Text(StringContentLoader -> "text/plain") {
125 fn new_static(&'static str);
127 fn new_alloc(String);
129 fn from_file();
131 }
132 type Binary(BytesContentLoader -> "application/octet-stream") {
134 fn new_static(&'static [u8]);
136 fn new_alloc(Vec<u8>);
138 fn from_file();
140 }
141}