use iron::Request;
use std::path::{PathBuf, Path};
use std::fs::{self, Metadata};
use std::convert::AsRef;
pub struct RequestedPath {
pub path: PathBuf,
}
impl RequestedPath {
pub fn new<P: AsRef<Path>>(root_path: P, request: &Request) -> RequestedPath {
let mut path = root_path.as_ref().to_path_buf();
path.extend(&request.url.path);
RequestedPath { path: path }
}
pub fn should_redirect(&self, metadata: &Metadata, request: &Request) -> bool {
let last_url_element = request.url.path
.last()
.map(|s| s.as_ref());
let has_trailing_slash = match last_url_element {
Some("") => true,
_ => false,
};
metadata.is_dir() && !has_trailing_slash
}
pub fn get_file(self, metadata: &Metadata) -> Option<PathBuf> {
if metadata.is_file() {
return Some(self.path);
}
let index_path = self.path.join("index.html");
match fs::metadata(&index_path) {
Ok(m) =>
if m.is_file() {
Some(index_path)
} else {
None
},
Err(_) => None,
}
}
}