little_hyper/
headers.rs

1use std::collections::HashMap;
2
3const HEADER_SEP: &str = ": ";
4const HEADER_CONTENT_TYPE: &str = "Content-Type";
5const HEADER_CONTENT_LEN: &str = "Content-Length";
6
7#[derive(Debug, Default)]
8pub struct Headers(HashMap<String, String>);
9
10impl Headers {
11    /// Get
12    ///
13    /// Get header value.
14    pub fn get(&self, key: &str) -> Option<&String> {
15        self.0.get(key)
16    }
17
18    /// Set
19    ///
20    /// Set header value.
21    pub fn set(&mut self, key: &str, value: &str) {
22        self.0.insert(key.to_string(), value.to_string());
23    }
24
25    /// Raw Header
26    ///
27    /// Used for writing response.
28    pub fn raw_headers(&self) -> String {
29        self.0
30            .iter()
31            .map(|(key, value)| format!("{}{}{}", key, HEADER_SEP, value))
32            .collect::<Vec<String>>()
33            .join("\n")
34    }
35
36    pub fn content_type(&mut self) -> Option<&String> {
37        self.get(HEADER_CONTENT_TYPE)
38    }
39    pub fn set_content_type(&mut self, content_type: &str) {
40        self.set(HEADER_CONTENT_TYPE, content_type)
41    }
42
43    pub fn content_len(&mut self) -> Option<&String> {
44        self.get(HEADER_CONTENT_LEN)
45    }
46    pub fn set_content_len(&mut self, content_len: &str) {
47        self.set(HEADER_CONTENT_LEN, content_len)
48    }
49}
50
51impl From<&[String]> for Headers {
52    fn from(value: &[String]) -> Self {
53        let mut headers = Headers::default();
54
55        for item in value {
56            let (key, value) = item.split_once(HEADER_SEP).expect("ERROR: ReadHeader");
57
58            headers.set(key, value);
59        }
60
61        headers
62    }
63}