#![cfg(feature = "ui")]
use std::path::Path;
use super::request::Request;
use super::response::{ContentType, Response, ResponseBuilder};
use self::assets::{ASSETS, Asset};
const BASE_URL: &str = "/ui";
const CATCH_ALL_URL: &str = "index.html";
pub fn handle_get_or_head(req: Request) -> Result<Response, Request> {
let head = req.is_head();
if req.uri().path() == "/" {
return Ok(Response::moved_permanently("/ui/"))
}
let req_path = Path::new(req.uri().path());
if let Ok(p) = req_path.strip_prefix(BASE_URL) {
match get_asset(p) {
Some(asset) => Ok(serve(head, asset)),
None => {
if let Some(default) = get_asset(Path::new(CATCH_ALL_URL)) {
Ok(serve(head, default))
}
else {
Ok(Response::not_found(false))
}
}
}
} else {
Ok(Response::not_found(false))
}
}
fn get_asset(path: &Path) -> Option<&Asset> {
let path = path.to_str()?;
ASSETS.iter().find(|asset| asset.path == path)
}
fn serve(head: bool, asset: &Asset) -> Response {
let res = ResponseBuilder::ok().content_type(
ContentType::external(asset.media_type.as_bytes())
);
if head {
res.empty()
}
else {
res.body(asset.content)
}
}
mod assets {
include!(concat!(env!("OUT_DIR"), "/ui_assets.rs"));
}