use std::fmt;
use { Method };
pub use hyper::server::Request as HttpRequest;
use hyper::uri::RequestUri::AbsolutePath;
macro_rules! try_err(
($e:expr) => {{
match $e {
Ok(v) => v,
Err(e) => { return Err(format!("Error: {}", e).to_string()); }
}
}}
);
pub struct Request {
pub url: String,
pub body: String,
pub method: Method
}
impl Request {
pub fn from_http(mut req: HttpRequest) -> Result<Request, String> {
let url = match req.uri {
AbsolutePath(ref url) => url.to_string(),
_ => return Err("Unsupported request URI".to_string())
};
let body = match req.read_to_end() {
Ok(body) => try_err!(String::from_utf8(body)),
Err(_) => return Err("Invalid body".to_string())
};
Ok(Request {
url: url,
body: body,
method: req.method
})
}
pub fn route(&self) -> (Method, &str) {
(self.method.clone(), &self.url)
}
}
impl fmt::Debug for Request {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "Request {{"));
try!(writeln!(f, " url: {}", self.url));
try!(writeln!(f, " method: {:?}", self.method));
try!(writeln!(f, " body: {}", self.body));
try!(write!(f, "}}"));
Ok(())
}
}