rouille/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::Request;
32/// use rouille::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 tolerant to what is accepted?
41pub fn cookies(request: &Request) -> CookiesIter {
42 let header = request.header("Cookie").unwrap_or("");
43
44 CookiesIter {
45 iter: header.split(';'),
46 }
47}
48
49/// Iterator that returns the list of cookies of a request.
50///
51/// See [the `cookies` functions](fn.cookies.html).
52pub struct CookiesIter<'a> {
53 iter: Split<'a, char>,
54}
55
56impl<'a> Iterator for CookiesIter<'a> {
57 type Item = (&'a str, &'a str);
58
59 fn next(&mut self) -> Option<Self::Item> {
60 loop {
61 let cookie = match self.iter.next() {
62 Some(c) => c,
63 None => return None,
64 };
65
66 let mut splits = cookie.splitn(2, |c| c == '=');
67 let key = match splits.next() {
68 None => continue,
69 Some(v) => v,
70 };
71 let value = match splits.next() {
72 None => continue,
73 Some(v) => v,
74 };
75
76 let key = key.trim();
77 let value = value.trim().trim_matches(|c| c == '"');
78
79 return Some((key, value));
80 }
81 }
82
83 #[inline]
84 fn size_hint(&self) -> (usize, Option<usize>) {
85 let (_, len) = self.iter.size_hint();
86 (0, len)
87 }
88}
89
90#[cfg(test)]
91mod test {
92 use super::cookies;
93 use Request;
94
95 #[test]
96 fn no_cookie() {
97 let request = Request::fake_http("GET", "/", vec![], Vec::new());
98 assert_eq!(cookies(&request).count(), 0);
99 }
100
101 #[test]
102 fn cookies_ok() {
103 let request = Request::fake_http(
104 "GET",
105 "/",
106 vec![("Cookie".to_owned(), "a=b; hello=world".to_owned())],
107 Vec::new(),
108 );
109
110 assert_eq!(
111 cookies(&request).collect::<Vec<_>>(),
112 vec![("a".into(), "b".into()), ("hello".into(), "world".into())]
113 );
114 }
115}