Skip to content

Commit

Permalink
Merge pull request #45 from lomirus/fix-404-page
Browse files Browse the repository at this point in the history
Add error page
  • Loading branch information
lomirus authored Dec 18, 2023
2 parents e9d4adf + 0058ee1 commit f485a04
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ struct Args {
#[clap(default_value = ".")]
root: String,
/// Set the listener host [default: LAN IP address]
#[clap(short='s', long)]
#[clap(short = 's', long)]
host: Option<String>,
/// Set the listener port
#[clap(short, long, default_value_t = 8000)]
Expand Down
18 changes: 14 additions & 4 deletions src/server.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::{collections::HashMap, io::ErrorKind};

use async_std::{fs, path::PathBuf, prelude::*, sync::Mutex};
use tide::{listener::Listener, Body, Request, Response, StatusCode};
Expand Down Expand Up @@ -103,12 +103,23 @@ async fn static_assets(
path.push("index.html");
}
let mime = mime_guess::from_path(&path).first_or_text_plain();
let mut response = Response::new(StatusCode::InternalServerError);
response.set_content_type(mime.to_string().as_str());

// Read the file.
let mut file = match fs::read(&path).await {
Ok(file) => file,
Err(err) => {
log::warn!("{}", err);
if mime == "text/html" {
let script = format!(include_str!("templates/websocket.html"), host, port);
let html = format!(include_str!("templates/error.html"), script, err);
response.set_body(Body::from_string(html));
if err.kind() == ErrorKind::NotFound {
response.set_status(StatusCode::NotFound);
}
return Ok(response);
}
return Err(tide::Error::new(StatusCode::NotFound, err));
}
};
Expand All @@ -122,11 +133,10 @@ async fn static_assets(
return Err(tide::Error::from_str(StatusCode::InternalServerError, err));
}
};
let script = format!(include_str!("scripts/websocket.html"), host, port);
let script = format!(include_str!("templates/websocket.html"), host, port);
file = format!("{text}{script}").into_bytes();
}
let mut response: Response = Body::from_bytes(file).into();
response.set_content_type(mime.to_string().as_str());
response.set_body(Body::from_bytes(file));

Ok(response)
}
8 changes: 8 additions & 0 deletions src/templates/error.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html>
<head>
<title>Live Server Error</title>
{}
</head>
<body>{}</body>
</html>
File renamed without changes.

0 comments on commit f485a04

Please sign in to comment.