h10/http/headers/entity/
content_type.rs

1use std::str::FromStr;
2
3use crate::http::{
4    headers::{HeaderEntry, HeaderName, HeaderValue, IntoHeader},
5    result::H10LibError,
6};
7
8/// ### Content-Type header
9/// Related: Entity-Body
10///
11///  The Content-Type entity-header field indicates the media type of the
12/// Entity-Body sent to the recipient or, in the case of the HEAD method, the
13/// media type that would have been sent had the request been a GET.
14///
15///  If the media type remains unknown, the recipient should treat it as type
16/// "application/octet-stream".
17///
18/// **Reference:** https://www.rfc-editor.org/rfc/rfc1945.html#section-10.5
19///
20#[derive(Debug, PartialEq, Eq)]
21pub struct ContentType {
22    name: HeaderName,
23    value: HeaderValue,
24}
25
26impl Default for ContentType {
27    fn default() -> Self {
28        Self {
29            name: HeaderName::new_unchecked("Content-Type"),
30            value: HeaderValue::new_unchecked("Not_Defined"),
31        }
32    }
33}
34impl ContentType {
35    pub fn octet_stream() -> Self {
36        Self {
37            value: HeaderValue::new_unchecked("application/octet-stream"),
38            ..Default::default()
39        }
40    }
41    pub fn html() -> Self {
42        Self {
43            value: HeaderValue::new_unchecked("text/html; charset=UTF-8"),
44            ..Default::default()
45        }
46    }
47
48    pub fn css() -> Self {
49        Self {
50            value: HeaderValue::new_unchecked("text/css; charset=UTF-8"),
51            ..Default::default()
52        }
53    }
54
55    pub fn javascript() -> Self {
56        Self {
57            value: HeaderValue::new_unchecked("application/javascript; charset=UTF-8"),
58            ..Default::default()
59        }
60    }
61    pub fn json() -> Self {
62        Self {
63            value: HeaderValue::new_unchecked("application/json; charset=UTF-8"),
64            ..Default::default()
65        }
66    }
67    pub fn form_url_encoded() -> Self {
68        Self {
69            value: HeaderValue::new_unchecked("application/x-www-form-urlencoded"),
70            ..Default::default()
71        }
72    }
73}
74
75impl FromStr for ContentType {
76    type Err = H10LibError;
77
78    fn from_str(s: &str) -> Result<Self, Self::Err> {
79        let entry: HeaderEntry = s.parse()?;
80        Ok(entry.into())
81    }
82}
83
84impl From<HeaderEntry> for ContentType {
85    fn from(value: HeaderEntry) -> Self {
86        let HeaderEntry { name, value } = value;
87        Self { name, value }
88    }
89}
90
91impl IntoHeader for ContentType {
92    fn into_header(self) -> HeaderEntry {
93        let Self { name, value } = self;
94        HeaderEntry { name, value }
95    }
96}