http_type/content_type/
impl.rs1use crate::*;
2
3impl ContentType {
5 fn get_application_json<T>(data: &T) -> String
15 where
16 T: Serialize + Display,
17 {
18 json_to_string(data).unwrap_or_else(|_| "{}".to_string())
19 }
20
21 fn get_application_xml<T>(data: &T) -> String
31 where
32 T: Serialize + Display,
33 {
34 serde_xml_rs::to_string(data).unwrap_or_else(|_| "<root></root>".to_string())
35 }
36
37 fn get_text_plain<T>(data: &T) -> String
47 where
48 T: Serialize + Debug + Clone + Default + Display,
49 {
50 data.to_string()
51 }
52
53 fn get_text_html<T>(data: &T) -> String
63 where
64 T: Serialize + Debug + Clone + Default,
65 {
66 let mut html: String = String::with_capacity(64);
67 html.push_str("<table><tr><td>");
68 html.push_str(&format!("{:?}", data));
69 html.push_str("</td></tr></table>");
70 html
71 }
72
73 fn get_form_url_encoded<T>(data: &T) -> String
83 where
84 T: Serialize + Display,
85 {
86 serde_urlencoded::to_string(data).unwrap_or_else(|_| String::new())
87 }
88
89 fn get_binary<T>(data: &T) -> String
99 where
100 T: Serialize + Debug + Clone + Default + Display,
101 {
102 hex::encode(data.to_string())
103 }
104
105 pub fn get_body_string<T>(&self, data: &T) -> String
115 where
116 T: Serialize + Debug + Clone + Default + Display,
117 {
118 match self {
119 Self::ApplicationJson => Self::get_application_json(data),
120 Self::ApplicationXml => Self::get_application_xml(data),
121 Self::TextPlain => Self::get_text_plain(data),
122 Self::TextHtml => Self::get_text_html(data),
123 Self::FormUrlEncoded => Self::get_form_url_encoded(data),
124 Self::Unknown => Self::get_binary(data),
125 }
126 }
127
128 pub fn format_content_type_with_charset(content_type: &str, charset: &str) -> String {
139 let mut result: String = String::with_capacity(
140 content_type.len() + SEMICOLON_SPACE.len() + CHARSET_EQUAL.len() + charset.len(),
141 );
142 result.push_str(content_type);
143 result.push_str(SEMICOLON_SPACE);
144 result.push_str(CHARSET_EQUAL);
145 result.push_str(charset);
146 result
147 }
148
149 pub fn format_content_type_with_charset_declaration(
160 content_type: &str,
161 charset_with_key: &str,
162 ) -> String {
163 let mut result: String = String::with_capacity(
164 content_type.len() + SEMICOLON_SPACE.len() + charset_with_key.len(),
165 );
166 result.push_str(content_type);
167 result.push_str(SEMICOLON_SPACE);
168 result.push_str(charset_with_key);
169 result
170 }
171}
172
173impl FromStr for ContentType {
175 type Err = ();
176
177 fn from_str(data: &str) -> Result<Self, Self::Err> {
187 match data.to_ascii_lowercase().as_str() {
188 APPLICATION_JSON => Ok(Self::ApplicationJson),
189 APPLICATION_XML => Ok(Self::ApplicationXml),
190 TEXT_PLAIN => Ok(Self::TextPlain),
191 TEXT_HTML => Ok(Self::TextHtml),
192 FORM_URLENCODED => Ok(Self::FormUrlEncoded),
193 _ => Ok(Self::Unknown),
194 }
195 }
196}