atlas_http/
cookie.rs

1#[derive(Debug, Clone)]
2pub struct Cookie {
3    pub host: String,
4    pub path: String,
5    pub http_only: bool,
6    pub secure: bool,
7    pub expires: u64,
8    pub name: String,
9    pub value: String,
10}
11
12impl Cookie {
13    /// Instantiate new cookie, used chained methods to specify other cookie variables.
14    pub fn new(name: &str, value: &str) -> Self {
15        Self {
16            host: String::new(),
17            path: "/".to_string(),
18            http_only: false,
19            secure: true,
20            expires: 0_u64,
21            name: name.to_string(),
22            value: value.to_string(),
23        }
24    }
25
26    /// Instantiate cookie from line of Netscape formatted cookies.txt file
27    pub fn from_line(line: &str) -> Option<Self> {
28        let parts: Vec<String> = line.trim().split('\t').map(|e| e.to_string()).collect();
29
30        if parts.len() < 7 {
31            return None;
32        }
33
34        // Set cookie
35        Some(Self {
36            host: parts[0].to_string(),
37            path: parts[2].to_string(),
38            http_only: parts[1].to_lowercase().as_str() != "false",
39            secure: parts[3].to_lowercase().as_str() != "false",
40            expires: parts[4].parse::<u64>().unwrap(),
41            name: parts[5].to_string(),
42            value: parts[6].to_string(),
43        })
44    }
45
46    /// Format cookie as line to be saved within Netscape formatted cookies.txt file
47    pub fn to_line(&self) -> String {
48        // Get line
49        let parts: Vec<String> = vec![
50            self.host.clone(),
51            if self.http_only {
52                "TRUE".to_string()
53            } else {
54                "FALSE".to_string()
55            },
56            self.path.clone(),
57            if self.secure {
58                "TRUE".to_string()
59            } else {
60                "FALSE".to_string()
61            },
62            format!("{}", self.expires),
63            self.name.clone(),
64            self.value.clone(),
65        ];
66
67        parts.join("\t").to_string()
68    }
69
70    /// Set host
71    pub fn host(mut self, host: &str) -> Self {
72        self.host = host.to_string();
73        self
74    }
75
76    /// Set path
77    pub fn path(mut self, path: &str) -> Self {
78        self.path = path.to_string();
79        self
80    }
81
82    /// Set http-only
83    pub fn http_only(mut self, http_only: bool) -> Self {
84        self.http_only = http_only;
85        self
86    }
87
88    /// Set secure
89    pub fn secure(mut self, secure: bool) -> Self {
90        self.secure = secure;
91        self
92    }
93
94    /// Set expires
95    pub fn expires(mut self, expires: u64) -> Self {
96        self.expires = expires;
97        self
98    }
99}