Skip to content

Commit

Permalink
Static dir serving: Look for HTML file if requested path isn't a dir …
Browse files Browse the repository at this point in the history
…and has no extension + Return 404 if file is not found
  • Loading branch information
Padi2312 committed Mar 18, 2024
1 parent fafc87b commit 70c543f
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "surfer"
version = "0.3.1"
version = "0.3.2"
edition = "2021"
description = "A small backend \"framework\" for Rust"
authors = ["Patrand"]
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Clone the repository and add the following to your `Cargo.toml`:

```toml
[dependencies]
surfer = "0.3.1"
surfer = "0.3.2"
```

## 📚 Example Usage
Expand Down
21 changes: 21 additions & 0 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,12 +180,33 @@ impl Server {
dir_path: PathBuf,
relative_path: String,
) -> Response {
// TODO: I should definitely refactor this method
let file_path = dir_path.clone();
let mut file_path = file_path.join(relative_path.trim_start_matches('/'));
// If the requested path is a directory, try to serve an index.html file
if file_path.is_dir().await || relative_path.is_empty() || relative_path.ends_with("/") {
file_path.push("index.html");
}

// If requested path has no extension, try to serve an HTML file
if file_path.extension().is_none() {
// HTML File check
let html_file_path = file_path.clone();
let html_file_path =
PathBuf::from(format!("{}.html", html_file_path.to_string_lossy()));
if html_file_path.exists().await {
file_path = html_file_path;
}
}

if !file_path.exists().await {
return Response {
status_code: 404,
headers: headers!(("Content-Type", "text/plain")),
body: Some(b"404 Not Found".to_vec()),
};
}

FileResponse {
status_code: 200,
headers: None,
Expand Down

0 comments on commit 70c543f

Please sign in to comment.