rouille_ng/input/cookies.rs
1// Copyright (c) 2016 The Rouille developers
2// Licensed under the Apache License, Version 2.0
3// <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
6// at your option. All files in the project carrying such
7// notice may not be copied, modified, or distributed except
8// according to those terms.
9
10//! Analyze the request's headers and body.
11//!
12//! This module provides functions and sub-modules that allow you to easily analyze or parse the
13//! request's headers and body.
14//!
15//! - In order to parse JSON, see [the `json` module](json/input.html).
16//! - In order to parse input from HTML forms, see [the `post` module](post/input.html).
17//! - In order to read a plain text body, see
18//! [the `plain_text_body` function](fn.plain_text_body.html).
19
20use std::str::Split;
21use Request;
22
23/// Attempts to parse the list of cookies from the request.
24///
25/// Returns an iterator that produces a pair of `(key, value)`. If the header is missing or
26/// malformed, an empty iterator is returned.
27///
28/// # Example
29///
30/// ```
31/// use rouille_ng::Request;
32/// use rouille_ng::input;
33///
34/// # let request: Request = return;
35/// if let Some((_, val)) = input::cookies(&request).find(|&(n, _)| n == "cookie-name") {
36/// println!("Value of cookie = {:?}", val);
37/// }
38/// ```
39// TODO: should an error be returned if the header is malformed?
40// TODO: be less tolerent to what is accepted?
41pub fn cookies(request: &Request) -> CookiesIter {
42 let header = match request.header("Cookie") {
43 None => "",
44 Some(h) => h,
45 };
46
47 CookiesIter {
48 iter: header.split(';'),
49 }
50}
51
52/// Iterator that returns the list of cookies of a request.
53///
54/// See [the `cookies` functions](fn.cookies.html).
55pub struct CookiesIter<'a> {
56 iter: Split<'a, char>,
57}
58
59impl<'a> Iterator for CookiesIter<'a> {
60 type Item = (&'a str, &'a str);
61
62 fn next(&mut self) -> Option<Self::Item> {
63 loop {
64 let cookie = match self.iter.next() {
65 Some(c) => c,
66 None => return None,
67 };
68
69 let mut splits = cookie.splitn(2, |c| c == '=');
70 let key = match splits.next() {
71 None => continue,
72 Some(v) => v,
73 };
74 let value = match splits.next() {
75 None => continue,
76 Some(v) => v,
77 };
78
79 let key = key.trim();
80 let value = value.trim().trim_matches(|c| c == '"');
81
82 return Some((key, value));
83 }
84 }
85
86 #[inline]
87 fn size_hint(&self) -> (usize, Option<usize>) {
88 let (_, len) = self.iter.size_hint();
89 (0, len)
90 }
91}
92
93#[cfg(test)]
94mod test {
95 use super::cookies;
96 use Request;
97
98 #[test]
99 fn no_cookie() {
100 let request = Request::fake_http("GET", "/", vec![], Vec::new());
101 assert_eq!(cookies(&request).count(), 0);
102 }
103
104 #[test]
105 fn cookies_ok() {
106 let request = Request::fake_http(
107 "GET",
108 "/",
109 vec![("Cookie".to_owned(), "a=b; hello=world".to_owned())],
110 Vec::new(),
111 );
112
113 assert_eq!(
114 cookies(&request).collect::<Vec<_>>(),
115 vec![("a".into(), "b".into()), ("hello".into(), "world".into())]
116 );
117 }
118}