Skip to content

Commit

Permalink
feature: add tower-http support
Browse files Browse the repository at this point in the history
  • Loading branch information
tyrchen committed Mar 25, 2024
1 parent c76f146 commit 7b16765
Show file tree
Hide file tree
Showing 4 changed files with 206 additions and 3 deletions.
177 changes: 177 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.114"
serde_yaml = "0.9.33"
tokio = { version = "1.36.0", features = ["rt", "rt-multi-thread", "macros", "net", "fs"] }
tower-http = { version = "0.5.2", features = ["compression-full", "cors", "trace", "fs"] }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
zxcvbn = "2.2.2"
23 changes: 22 additions & 1 deletion src/process/http_serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use axum::{
Router,
};
use std::{net::SocketAddr, path::PathBuf, sync::Arc};
use tower_http::services::ServeDir;
use tracing::{info, warn};

#[derive(Debug)]
Expand All @@ -17,9 +18,10 @@ pub async fn process_http_serve(path: PathBuf, port: u16) -> Result<()> {
let addr = SocketAddr::from(([0, 0, 0, 0], port));
info!("Serving {:?} on {}", path, addr);

let state = HttpServeState { path };
let state = HttpServeState { path: path.clone() };
// axum router
let router = Router::new()
.nest_service("/tower", ServeDir::new(path))
.route("/*path", get(file_handler))
.with_state(Arc::new(state));

Expand All @@ -40,6 +42,10 @@ async fn file_handler(
format!("File {} note found", p.display()),
)
} else {
// TODO: test p is a directory
// if it is a directory, list all files/subdirectories
// as <li><a href="/path/to/file">file name</a></li>
// <html><body><ul>...</ul></body></html>
match tokio::fs::read_to_string(p).await {
Ok(content) => {
info!("Read {} bytes", content.len());
Expand All @@ -52,3 +58,18 @@ async fn file_handler(
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[tokio::test]
async fn test_file_handler() {
let state = Arc::new(HttpServeState {
path: PathBuf::from("."),
});
let (status, content) = file_handler(State(state), Path("Cargo.toml".to_string())).await;
assert_eq!(status, StatusCode::OK);
assert!(content.trim().starts_with("[package]"));
}
}
8 changes: 6 additions & 2 deletions test.rest
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
### Test index page
### Test static file

GET http://localhost:8080/fixtures/ed25519.pk
GET http://localhost:8080/Cargo.toml

### Test static file with tower-http

GET http://localhost:8080/tower/fixtures/ed25519.pk

0 comments on commit 7b16765

Please sign in to comment.