Skip to content

Commit

Permalink
Add index_on_subdirectories option
Browse files Browse the repository at this point in the history
  • Loading branch information
marlonbaeten committed Jul 22, 2024
1 parent 4a58a1d commit f44de67
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 15 deletions.
23 changes: 12 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,18 @@ async fn main() {
An instance of the `MemoryServe` struct can be configured by calling
the following configuration methods:

| method | Default value | Description |
| ----------------------------------- | ----------------------- | ---------------------------------------------------- |
| [`MemoryServe::index_file`] | `Some("/index.html")` | Which file to serve on the route "/" |
| [`MemoryServe::fallback`] | `None` | Which file to serve if no routed matched the request |
| [`MemoryServe::fallback_status`] | `StatusCode::NOT_FOUND` | The HTTP status code to routes that did not match |
| [`MemoryServe::enable_gzip`] | `true` | Allow to serve gzip encoded files |
| [`MemoryServe::enable_brotli`] | `true` | Allow to serve brotli encoded files |
| [`MemoryServe::html_cache_control`] | `CacheControl::Short` | Cache control header to serve on HTML files |
| [`MemoryServe::cache_control`] | `CacheControl::Medium` | Cache control header to serve on other files |
| [`MemoryServe::add_alias`] | `[]` | Create a route / file alias |
| [`MemoryServe::enable_clean_url`] | `false` | Enable clean URLs |
| method | Default value | Description |
| ---------------------------------------- | ----------------------- | ---------------------------------------------------------- |
| [`MemoryServe::index_file`] | `Some("/index.html")` | Which file to serve on the route "/" |
| [`MemoryServe::index_on_subdirectories`] | `false` | Whether to serve the corresponding index in subdirectories |
| [`MemoryServe::fallback`] | `None` | Which file to serve if no routed matched the request |
| [`MemoryServe::fallback_status`] | `StatusCode::NOT_FOUND` | The HTTP status code to routes that did not match |
| [`MemoryServe::enable_gzip`] | `true` | Allow to serve gzip encoded files |
| [`MemoryServe::enable_brotli`] | `true` | Allow to serve brotli encoded files |
| [`MemoryServe::html_cache_control`] | `CacheControl::Short` | Cache control header to serve on HTML files |
| [`MemoryServe::cache_control`] | `CacheControl::Medium` | Cache control header to serve on other files |
| [`MemoryServe::add_alias`] | `[]` | Create a route / file alias |
| [`MemoryServe::enable_clean_url`] | `false` | Enable clean URLs |

See [`Cache control`](#cache-control) for the cache control options.

Expand Down
47 changes: 43 additions & 4 deletions memory-serve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub use memory_serve_macros::load_assets;
#[derive(Debug, Clone, Copy)]
struct ServeOptions {
index_file: Option<&'static str>,
index_on_subdirectories: bool,
fallback: Option<&'static str>,
fallback_status: StatusCode,
html_cache_control: CacheControl,
Expand All @@ -35,6 +36,7 @@ impl Default for ServeOptions {
fn default() -> Self {
Self {
index_file: Some("/index.html"),
index_on_subdirectories: false,
fallback: None,
fallback_status: StatusCode::NOT_FOUND,
html_cache_control: CacheControl::Short,
Expand Down Expand Up @@ -78,6 +80,14 @@ impl MemoryServe {
self
}

/// Whether to serve the corresponding index.html file when a route
/// matches a subdirectory
pub fn index_on_subdirectories(mut self, enable: bool) -> Self {
self.options.index_on_subdirectories = enable;

self
}

/// Which static file to serve when no other routes are matched, also see
/// [fallback](https://docs.rs/axum/latest/axum/routing/struct.Router.html#method.fallback)
/// The path (or route) should be relative to the directory passed to
Expand Down Expand Up @@ -200,10 +210,17 @@ impl MemoryServe {
});
}

if Some(asset.route) == options.index_file {
info!("serving {} as index on /", asset.route);
if let Some(index) = options.index_file {
if asset.route == index {
info!("serving {} as index on /", asset.route);

router = router.route("/", get(handler));
} else if options.index_on_subdirectories && asset.route.ends_with(index) {
let path = &asset.route[..asset.route.len() - index.len()];
info!("serving {} as index on {}", asset.route, path);

router = router.route("/", get(handler));
router = router.route(path, get(handler));
}
}

let path = if options.enable_clean_url && asset.route.ends_with(".html") {
Expand Down Expand Up @@ -281,6 +298,7 @@ mod tests {
"/assets/index.css",
"/assets/index.js",
"/assets/stars.svg",
"/blog/index.html",
"/index.html"
]
);
Expand All @@ -292,11 +310,12 @@ mod tests {
"text/css",
"text/javascript",
"image/svg+xml",
"text/html",
"text/html"
]
);
if cfg!(debug_assertions) {
assert_eq!(etags, ["", "", "", "", "", ""]);
assert_eq!(etags, ["", "", "", "", "", "", ""]);
} else {
assert_eq!(
etags,
Expand All @@ -306,6 +325,7 @@ mod tests {
"ec4edeea111c854901385011f403e1259e3f1ba016dcceabb6d566316be3677b",
"86a7fdfd19700843e5f7344a63d27e0b729c2554c8572903ceee71f5658d2ecf",
"bd9dccc152de48cb7bedc35b9748ceeade492f6f904710f9c5d480bd6299cc7d",
"89e9873a8e49f962fe83ad2bfe6ac9b21ef7c1b4040b99c34eb783dccbadebc5",
"0639dc8aac157b58c74f65bbb026b2fd42bc81d9a0a64141df456fa23c214537"
]
);
Expand Down Expand Up @@ -421,6 +441,25 @@ mod tests {
assert_eq!(code, 200);
}

#[tokio::test]
async fn index_file_on_subdirs() {
let memory_router = MemoryServe::new(load_assets!("../static"))
.index_file(Some("/index.html"))
.index_on_subdirectories(false)
.into_router();

let (code, _) = get(memory_router.clone(), "/blog", "accept", "*").await;
assert_eq!(code, 404);

let memory_router = MemoryServe::new(load_assets!("../static"))
.index_file(Some("/index.html"))
.index_on_subdirectories(true)
.into_router();

let (code, _) = get(memory_router.clone(), "/blog", "accept", "*").await;
assert_eq!(code, 200);
}

#[tokio::test]
async fn clean_url() {
let memory_router = MemoryServe::new(load_assets!("../static"))
Expand Down
14 changes: 14 additions & 0 deletions static/blog/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>RUST IS AWESOME</title>
<script type="module" crossorigin src="/assets/index.js"></script>
<link rel="stylesheet" href="/assets/index.css">
<link rel="icon" type="image/jpeg" href="/assets/icon.jpg">
</head>
<body>
<h1>Blog Page</h1>
</body>
</html>

0 comments on commit f44de67

Please sign in to comment.