use std::collections::HashMap;
use std::io::{empty, Read, BufReader};
use parser;
use http::{Method, Version, Header, Error};
pub struct Request {
pub method: Method,
pub path: String,
pub version: Version,
pub headers: HashMap<Header, String>,
pub body: Box<Read>,
}
impl Request {
pub fn new<P: Into<String>>(method: Method, path: P) -> Self {
Request {
method: method,
path: path.into(),
version: Version::Http11,
headers: HashMap::new(),
body: Box::new(empty()),
}
}
pub fn from_reader(reader: &mut Read) -> Result<Self, Error> {
let mut reader = BufReader::new(reader);
let (method, path, version) = try!(parser::request_line::parse(&mut reader));
let headers = try!(parser::headers::parse(&mut reader));
let request = Request {
method: method,
path: path,
version: version,
headers: headers,
body: Box::new(empty()),
};
Ok(request)
}
pub fn set_header<F: Into<Header>, V: Into<String>>(&mut self, field: F, value: V) -> &mut Self {
self.headers.insert(field.into(), value.into());
self
}
}
#[cfg(test)]
mod tests {
use super::Request;
use http::{Method, Version, Header};
#[test]
fn test_new_request() {
let req = Request::new(Method::Get, "/");
assert_eq!(Method::Get, req.method);
assert_eq!("/".to_owned(), req.path);
assert_eq!(Version::Http11, req.version);
}
#[test]
fn test_set_header_from_str_to_str() {
let mut req = Request::new(Method::Get, "/");
req.set_header("content-type", "application/json");
let value = req.headers.get(&"content-type".into());
assert_eq!(Some(&"application/json".to_owned()), value);
}
#[test]
fn test_set_header_from_header_to_str() {
let mut req = Request::new(Method::Get, "/");
req.set_header(Header::ContentType, "application/json");
let value = req.headers.get(&"content-type".into());
assert_eq!(Some(&"application/json".to_owned()), value);
}
#[test]
fn test_set_header_from_header_to_string() {
let mut req = Request::new(Method::Get, "/");
req.set_header(Header::ContentType, "application/json".to_owned());
let value = req.headers.get(&"content-type".into());
assert_eq!(Some(&"application/json".to_owned()), value);
}
}