nova_core/types/
headers.rs1use std::collections::HashMap;
2use std::fmt::{Display, Formatter};
3
4use crate::errors::ServerError;
5use crate::ext::hash_map_ext::HashMapExt;
6use crate::validators::has_error::ValidateHasError;
7
8#[derive(Clone, Debug, Default)]
10pub struct Headers {
11 inner: HashMap<String, String>,
12}
13
14impl HashMapExt for Headers {
15 fn new(inner: HashMap<String, String>) -> Self {
16 Self { inner }
17 }
18
19 fn get_inner(&self) -> HashMap<String, String> {
20 self.inner.clone()
21 }
22
23 fn insert(&mut self, k: &str, v: &str) {
24 self.inner.insert(k.to_string(), v.to_string());
25 }
26
27 fn insert_if_not_exists(&mut self, k: &str, v: &str) {
28 if !self.contains_key(k) {
29 self.inner.insert(k.to_string(), v.to_string());
30 }
31 }
32
33 fn from_str(str: &str) -> Result<Self, ServerError> {
34 let inner = str
35 .split("\r\n")
36 .filter(|item| item.contains(": "))
37 .map(|item| {
38 let item = item.split(": ").collect::<Vec<&str>>();
39 if item.len() < 2 {
40 Err(ServerError::BadRequest {
41 message: "unable to parse headers".to_string(),
42 })
43 } else {
44 Ok((item[0].to_string(), item[1].to_string()))
45 }
46 })
47 .collect::<Vec<_>>()
48 .has_error()?
49 .into_iter()
50 .map(Result::unwrap)
51 .collect();
52 Ok(Self::new(inner))
53 }
54}
55
56impl Display for Headers {
57 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
58 write!(f, "{}", self.print())
59 }
60}